easycar.controller.BookingListController.java Source code

Java tutorial

Introduction

Here is the source code for easycar.controller.BookingListController.java

Source

package easycar.controller;

import java.io.IOException;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.primefaces.context.RequestContext;
import org.primefaces.event.DateSelectEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import easycar.dto.BookingDto;
import easycar.dto.CarDto;
import easycar.dto.CustomerDto;
import easycar.dto.FullBookingDto;
import easycar.dto.FullCarDto;
import easycar.dto.MaintenanceDto;
import easycar.dto.UserDto;
import easycar.model.BookingListModel;
import easycar.model.CarListModel;
import easycar.model.SimpleCarListModel;
import easycar.spec.manager.SessionManager;
import easycar.spec.service.BookingService;
import easycar.spec.service.CarService;
import easycar.spec.service.CustomerService;
import easycar.spec.service.MaintenanceService;
import easycar.spec.service.StoreEmployeeService;
import easycar.spec.service.UserService;
import easycar.utils.Fourth;
import easycar.utils.Pair;

@Named
@ConversationScoped
public class BookingListController implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -3672602821770471171L;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /* 'Conversation' object required in order to start a conversation scope
        See boolList.xhtml */
    @Inject
    private SessionManager sessionManager;

    @Inject
    private Conversation conversation;

    @Inject
    private StoreEmployeeService storeEmployeeService;

    @Inject
    private CustomerService customerService;

    @Inject
    private UserService userService;

    @Inject
    private BookingService bookingService;

    @Inject
    private CarService carService;

    @Inject
    private MaintenanceService maintenanceService;

    @Inject
    private DictionaryController dictionaryController;

    private List<FullBookingDto> baseFullBookingList = null;
    private BookingListModel bookingList;

    private List<FullBookingDto> baseFullReassignBookingList = null;
    private BookingListModel reassignBookingList;

    private List<FullBookingDto> baseTodayFullBookingList = null;
    private BookingListModel todayBookingList;

    private FullBookingDto selectedBooking; // For selecting row
    private List<FullBookingDto> filteredBookings; // For filtering row

    private FullBookingDto selectedTodayBooking; // For selecting row
    private List<FullBookingDto> filteredTodayBookings; // For filtering row

    private FullBookingDto reassignBooking; // For selecting row
    private List<FullBookingDto> filteredReassignBookings; // For filtering row

    private List<FullCarDto> filteredReassignCars; // For filtering row

    private FullBookingDto editBooking;

    private FullBookingDto editTodayBooking;

    private boolean editMode = false;

    private boolean todayEditMode = false;

    private int first;

    private int todayFirst;

    private Date startDateToRestore;
    private Date endDateToRestore;
    private String statusToRestore;
    private String remindRemarkToRestore;
    private String returnRemarkToRestore;

    private Map<String, Double> currencyMap;

    private UserDto currentUser;
    private int currentStoreId;

    private double newBookingAdjustmentCharge;
    private double newEditPrice;

    private int[] selectedParameters;

    private boolean reassignMode;
    private boolean afterCheck;

    private int reassignCarId;
    private String reassignDriverId;

    private String confirmMessage;

    private Vector<Pair<Integer, Integer>> conflictBookingList;

    private boolean driverOn;
    private String changeDriverId;

    private int reassignPage;

    private List<FullCarDto> baseCarList = null;
    private CarListModel carList;

    private List<CarDto> baseCurrentUsingCar = null;
    private SimpleCarListModel currentUsingCar;

    private FullCarDto reassignCar;

    private boolean overdueCharge;

    private double oldDamageCharge;
    private String oldDriverId;
    private double oldTotalPrice;

    private boolean carReassign; // Use to show available car table when reassign new car

    private Date filterStartDate;

    private boolean applyNewPrice;

    private boolean resolveConflictMode;

    private boolean validateFail;

    private List<SelectItem> statusOptions;
    private List<SelectItem> overdueOptions;

    private boolean returnCarMode;

    private boolean sendCarForMaintenance;

    private boolean deliverCarMode;

    public void initConversation() {
        if (!FacesContext.getCurrentInstance().isPostback() && conversation.isTransient()) {

            conversation.begin();
        }
    }

    @PostConstruct
    public void init() {
        currencyMap = new HashMap<String, Double>();

        try {
            String USER_AGENT = "Mozilla/5.0";
            URL obj;
            String url = "http://query.yahooapis.com/v1/public/yql?q=" + URLEncoder.encode(
                    "select * from yahoo.finance.xchange where pair in (\"USDEUR\", \"EURUSD\", \"USDJPY\", \"JPYUSD\", \"USDAUD\", \"AUDUSD\", \"USDHKD\", \"HKDUSD\", \"USDMYR\", \"MYRUSD\", \"USDNZD\", \"NZDUSD\", \"USDSGD\", \"SGDUSD\")",
                    "UTF-8") + "&env=store://datatables.org/alltableswithkeys";
            obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // optional default is GET
            con.setRequestMethod("GET");
            //add request header
            con.setRequestProperty("User-Agent", USER_AGENT);

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            // Process response
            Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(con.getInputStream());
            response.getDocumentElement().normalize();
            System.out.println("Root element :" + response.getDocumentElement().getNodeName());
            NodeList nList = response.getElementsByTagName("rate");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                //System.out.println("\nCurrent Element :" + nNode.getNodeName());
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    currencyMap.put(eElement.getAttribute("id"),
                            Double.valueOf(eElement.getElementsByTagName("Rate").item(0).getTextContent()));
                }
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        try {
            currentUser = sessionManager.getLoginUser();
            currentStoreId = storeEmployeeService.getStoreIdOfEmployee(currentUser.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }

        reassignCarId = -1;
        reassignDriverId = "";

        confirmMessage = "";
        conflictBookingList = new Vector<Pair<Integer, Integer>>();
        driverOn = false;
        reassignPage = 0;

        reassignCar = null;
        afterCheck = false;
        carReassign = false;

        overdueCharge = false;
        applyNewPrice = false;

        resolveConflictMode = false;

        validateFail = false;

        statusOptions = new ArrayList<SelectItem>();
        statusOptions.add(new SelectItem("", dictionaryController.getDictionary().get("ALL")));
        statusOptions.add(new SelectItem(dictionaryController.getDictionary().get("BOOKED"),
                dictionaryController.getDictionary().get("BOOKED")));
        statusOptions.add(new SelectItem(dictionaryController.getDictionary().get("SERVING"),
                dictionaryController.getDictionary().get("SERVING")));
        statusOptions.add(new SelectItem(dictionaryController.getDictionary().get("COMPLETED"),
                dictionaryController.getDictionary().get("COMPLETED")));
        statusOptions.add(new SelectItem(dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"),
                dictionaryController.getDictionary().get("NEED CAR REPLACEMENT")));
        statusOptions.add(new SelectItem(dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"),
                dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT")));
        statusOptions
                .add(new SelectItem(dictionaryController.getDictionary().get("NEED CAR AND DRIVER REPLACEMENT"),
                        dictionaryController.getDictionary().get("NEED CAR AND DRIVER REPLACEMENT")));
        statusOptions.add(new SelectItem(dictionaryController.getDictionary().get("UNRESOLVABLE"),
                dictionaryController.getDictionary().get("UNRESOLVABLE")));

        overdueOptions = new ArrayList<SelectItem>();
        overdueOptions.add(new SelectItem("", dictionaryController.getDictionary().get("ALL")));
        overdueOptions.add(new SelectItem(dictionaryController.getDictionary().get("Yes"),
                dictionaryController.getDictionary().get("Yes")));
        overdueOptions.add(new SelectItem(dictionaryController.getDictionary().get("No"),
                dictionaryController.getDictionary().get("No")));
    }

    public List<SelectItem> getStatusOptions() {
        return statusOptions;
    }

    public void setStatusOptions(List<SelectItem> statusOptions) {
        this.statusOptions = statusOptions;
    }

    public List<SelectItem> getOverdueOptions() {
        return overdueOptions;
    }

    public void setOverudeOptions(List<SelectItem> overdueOptions) {
        this.overdueOptions = overdueOptions;
    }

    public int getReassignPage() {
        return reassignPage;
    }

    public boolean isDriverOn() {
        return driverOn;
    }

    public void setDriverOn(boolean driverOn) {
        this.driverOn = driverOn;
    }

    public boolean isOverdueCharge() {
        return overdueCharge;
    }

    public void setOverdueCharge(boolean overdueCharge) {
        this.overdueCharge = overdueCharge;
    }

    public boolean isCarReassign() {
        return carReassign;
    }

    public boolean isApplyNewPrice() {
        return applyNewPrice;
    }

    public void setApplyNewPrice(boolean applyNewPrice) {
        this.applyNewPrice = applyNewPrice;
    }

    public boolean isConflictExist() {
        if (conflictBookingList.size() > 1 && resolveConflictMode) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isHasConflict() {
        if (conflictBookingList.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isReturnCarMode() {
        return returnCarMode;
    }

    public boolean isDeliverCarMode() {
        return deliverCarMode;
    }

    public String getConfirmMessage() {
        return confirmMessage;
    }

    public int getReassignCarId() {
        return reassignCarId;
    }

    public String getReassignDriverId() {
        return reassignDriverId;
    }

    public int[] getSelectedParameters() {
        return selectedParameters;
    }

    public void setSelectedParameters(int[] selectedParameters) {
        this.selectedParameters = selectedParameters;
    }

    public int getFirst() {
        return first;
    }

    public void setFirst(int first) {
        this.first = first;
    }

    public int getTodayFirst() {
        return todayFirst;
    }

    public void setTodayFirst(int todayFirst) {
        this.todayFirst = todayFirst;
    }

    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public boolean isTodayEditMode() {
        return todayEditMode;
    }

    public void setTodayEditMode(boolean todayEditMode) {
        this.todayEditMode = todayEditMode;
    }

    public boolean isReassignMode() {
        return reassignMode;
    }

    public void setReassignMode(boolean reassignMode) {
        this.reassignMode = reassignMode;
    }

    public boolean isAfterCheck() {
        return afterCheck;
    }

    public Date getFilterStartDate() {
        return filterStartDate;
    }

    public void setFilterStartDate(Date filterStartDate) {
        this.filterStartDate = filterStartDate;
    }

    public Date getMinDateForCalendar() {
        Date today = getZeroTimeDate(new Date());

        if (editMode && getZeroTimeDate(selectedBooking.getStartDate()).compareTo(today) < 0) {
            return selectedBooking.getStartDate();
        } else if (todayEditMode && getZeroTimeDate(selectedTodayBooking.getStartDate()).compareTo(today) < 0) {
            return selectedTodayBooking.getStartDate();
        }

        return today;
    }

    public CarListModel getCarList() {
        if (baseCarList == null) {
            baseCarList = new Vector<FullCarDto>();
            carList = new CarListModel(baseCarList);
        }
        return baseCarList == null ? new CarListModel(new ArrayList<FullCarDto>()) : carList;
    }

    public SimpleCarListModel getCurrentUsingCar() {
        if (baseCurrentUsingCar == null) {
            baseCurrentUsingCar = new Vector<CarDto>();
            currentUsingCar = new SimpleCarListModel(baseCurrentUsingCar);
        }
        return baseCurrentUsingCar == null ? new SimpleCarListModel(new ArrayList<CarDto>()) : currentUsingCar;
    }

    public BookingListModel getBookingList() {
        if (baseFullBookingList == null) {
            try {
                List<BookingDto> baseBookingList = bookingService.getBookingListByStoreId(currentStoreId);

                baseFullBookingList = new Vector<FullBookingDto>();
                FullBookingDto tempFullBookingDto = null;
                BookingDto currentBookingDto = null;
                CustomerDto currentCustomerDto = null;
                CarDto currentCarDto = null;
                String statusToDisplay = "";
                Date nextBookingDate = null;
                boolean carLate, driverLate;

                for (int i = 0; i < baseBookingList.size(); i++) {
                    currentBookingDto = baseBookingList.get(i);
                    currentCustomerDto = customerService.getCustomerById(currentBookingDto.getCustomerId());
                    currentCarDto = carService.getCarById(currentBookingDto.getCarId());

                    // Check if car and driver is available
                    if (getZeroTimeDate(currentBookingDto.getStartDate())
                            .compareTo(getZeroTimeDate(new Date())) == 0) {
                        carLate = false;
                        driverLate = false;
                        if (bookingService.isCarReturnedLate(currentBookingDto.getCarId(),
                                getZeroTimeDate(new Date()))) {
                            carLate = true;
                        }

                        if (currentBookingDto.getDriverId() != null
                                && currentBookingDto.getDriverId().compareTo("") != 0) {
                            if (bookingService.isDriverReturnedLate(currentBookingDto.getDriverId(),
                                    getZeroTimeDate(new Date()))) {
                                driverLate = true;
                            }
                        }

                        if (carLate && !driverLate
                                && currentBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") != 0
                                && currentBookingDto.getStatus()
                                        .compareTo("NEED CAR AND DRIVER REPLACEMENT") != 0) {
                            currentBookingDto.setStatus("NEED CAR REPLACEMENT");
                            bookingService.markBookingAsNeedCarReplacement(currentBookingDto.getId());
                        } else if (!carLate && driverLate
                                && currentBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") != 0
                                && currentBookingDto.getStatus()
                                        .compareTo("NEED CAR AND DRIVER REPLACEMENT") != 0) {
                            currentBookingDto.setStatus("NEED DRIVER REPLACEMENT");
                            bookingService.markBookingAsNeedDriverReplacement(currentBookingDto.getDriverId(),
                                    getZeroTimeDate(new Date()));
                        } else if (carLate && driverLate && currentBookingDto.getStatus()
                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") != 0) {
                            currentBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                            bookingService.markBookingAsNeedCarAndDriverReplacement(currentBookingDto.getId());
                        }
                    }

                    if (currentBookingDto.getStatus().compareTo("BOOKED") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("BOOKED");
                    } else if (currentBookingDto.getStatus().compareTo("SERVING") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("SERVING");
                    } else if (currentBookingDto.getStatus().compareTo("COMPLETED") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("COMPLETED");
                    } else if (currentBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("NEED CAR REPLACEMENT");
                    } else if (currentBookingDto.getStatus().compareTo("UNRESOLVABLE") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("UNRESOLVABLE");
                    } else if (currentBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT");
                    } else if (currentBookingDto.getStatus().compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                        statusToDisplay = dictionaryController.getDictionary()
                                .get("NEED CAR AND DRIVER REPLACEMENT");
                    }

                    // Find the next booking date of the car
                    if (currentBookingDto.getStatus().compareTo("SERVING") == 0) {
                        nextBookingDate = bookingService.getNextBookingDateOfCar(currentBookingDto.getCarId());
                    } else {
                        nextBookingDate = null;
                    }

                    tempFullBookingDto = new FullBookingDto(currentBookingDto.getId(),
                            currentBookingDto.getStoreId(), currentBookingDto.getCarId(),
                            currentCarDto.getPlateNumber(), currentBookingDto.getCustomerId(),
                            currentCustomerDto.getName(), currentCustomerDto.getDrivingLicense(),
                            currentCustomerDto.getEmail(), currentCustomerDto.getPhone(),
                            currentCustomerDto.getAddress(), currentBookingDto.getStartDate(),
                            currentBookingDto.getEndDate(), currentBookingDto.getDriverId(),
                            currentBookingDto.getDamageCharge(), currentBookingDto.getBookingAdjustmentCharge(),
                            currentBookingDto.getTotalPrice(), currentBookingDto.getStatus(), statusToDisplay,
                            currentBookingDto.getCurrency(), currentBookingDto.getLastEmailRemindDate(),
                            currentBookingDto.getLastPhoneRemindDate(), currentBookingDto.getRemindRemark(),
                            currentBookingDto.getDeliveryRemark(), currentBookingDto.getReturnRemark(),
                            nextBookingDate);
                    if (tempFullBookingDto.isOverdue()) {
                        tempFullBookingDto.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
                    } else {
                        tempFullBookingDto.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
                    }
                    baseFullBookingList.add(tempFullBookingDto);
                }
                bookingList = new BookingListModel(baseFullBookingList);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return baseFullBookingList == null ? new BookingListModel(new ArrayList<FullBookingDto>()) : bookingList;
    }

    public BookingListModel getReassignBookingList() {
        if (baseFullReassignBookingList == null) {
            baseFullReassignBookingList = new Vector<FullBookingDto>();
            reassignBookingList = new BookingListModel(baseFullReassignBookingList);
        }

        return baseFullReassignBookingList == null ? new BookingListModel(new ArrayList<FullBookingDto>())
                : reassignBookingList;
    }

    public BookingListModel getTodayBookingList() {
        if (baseTodayFullBookingList == null) {
            try {
                List<BookingDto> baseTodayBookingList = bookingService
                        .getBookingListOfOneDayByStoreId(currentStoreId, getZeroTimeDate(new Date()));

                baseTodayFullBookingList = new Vector<FullBookingDto>();
                FullBookingDto tempFullBookingDto = null;
                BookingDto currentBookingDto = null;
                CustomerDto currentCustomerDto = null;
                CarDto currentCarDto = null;
                String statusToDisplay = "";
                Date nextBookingDate = null;
                boolean carLate, driverLate;

                for (int i = 0; i < baseTodayBookingList.size(); i++) {
                    currentBookingDto = baseTodayBookingList.get(i);
                    currentCustomerDto = customerService.getCustomerById(currentBookingDto.getCustomerId());
                    currentCarDto = carService.getCarById(currentBookingDto.getCarId());

                    if (getZeroTimeDate(currentBookingDto.getStartDate())
                            .compareTo(getZeroTimeDate(new Date())) == 0) {
                        // Check if car and driver is available
                        carLate = false;
                        driverLate = false;
                        if (bookingService.isCarReturnedLate(currentBookingDto.getCarId(),
                                getZeroTimeDate(new Date()))) {
                            carLate = true;
                        }

                        if (currentBookingDto.getDriverId() != null
                                && currentBookingDto.getDriverId().compareTo("") != 0) {
                            if (bookingService.isDriverReturnedLate(currentBookingDto.getDriverId(),
                                    getZeroTimeDate(new Date()))) {
                                driverLate = true;
                            }
                        }

                        if (carLate && !driverLate
                                && currentBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") != 0
                                && currentBookingDto.getStatus()
                                        .compareTo("NEED CAR AND DRIVER REPLACEMENT") != 0) {
                            currentBookingDto.setStatus("NEED CAR REPLACEMENT");
                            bookingService.markBookingAsNeedCarReplacement(currentBookingDto.getId());
                        } else if (!carLate && driverLate
                                && currentBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") != 0
                                && currentBookingDto.getStatus()
                                        .compareTo("NEED CAR AND DRIVER REPLACEMENT") != 0) {
                            currentBookingDto.setStatus("NEED DRIVER REPLACEMENT");
                            bookingService.markBookingAsNeedDriverReplacement(currentBookingDto.getDriverId(),
                                    getZeroTimeDate(new Date()));
                        } else if (carLate && driverLate && currentBookingDto.getStatus()
                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") != 0) {
                            currentBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                            bookingService.markBookingAsNeedCarAndDriverReplacement(currentBookingDto.getId());
                        }
                    }

                    if (currentBookingDto.getStatus().compareTo("BOOKED") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("BOOKED");
                    } else if (currentBookingDto.getStatus().compareTo("SERVING") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("SERVING");
                    } else if (currentBookingDto.getStatus().compareTo("COMPLETED") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("COMPLETED");
                    } else if (currentBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("NEED CAR REPLACEMENT");
                    } else if (currentBookingDto.getStatus().compareTo("UNRESOLVABLE") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("UNRESOLVABLE");
                    } else if (currentBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0) {
                        statusToDisplay = dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT");
                    } else if (currentBookingDto.getStatus().compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                        statusToDisplay = dictionaryController.getDictionary()
                                .get("NEED CAR AND DRIVER REPLACEMENT");
                    }

                    // Find the next booking date of the car
                    if (currentBookingDto.getStatus().compareTo("SERVING") == 0) {
                        nextBookingDate = bookingService.getNextBookingDateOfCar(currentBookingDto.getCarId());
                    } else {
                        nextBookingDate = null;
                    }

                    tempFullBookingDto = new FullBookingDto(currentBookingDto.getId(),
                            currentBookingDto.getStoreId(), currentBookingDto.getCarId(),
                            currentCarDto.getPlateNumber(), currentBookingDto.getCustomerId(),
                            currentCustomerDto.getName(), currentCustomerDto.getDrivingLicense(),
                            currentCustomerDto.getEmail(), currentCustomerDto.getPhone(),
                            currentCustomerDto.getAddress(), currentBookingDto.getStartDate(),
                            currentBookingDto.getEndDate(), currentBookingDto.getDriverId(),
                            currentBookingDto.getDamageCharge(), currentBookingDto.getBookingAdjustmentCharge(),
                            currentBookingDto.getTotalPrice(), currentBookingDto.getStatus(), statusToDisplay,
                            currentBookingDto.getCurrency(), currentBookingDto.getLastEmailRemindDate(),
                            currentBookingDto.getLastPhoneRemindDate(), currentBookingDto.getRemindRemark(),
                            currentBookingDto.getDeliveryRemark(), currentBookingDto.getReturnRemark(),
                            nextBookingDate);
                    if (tempFullBookingDto.isOverdue()) {
                        tempFullBookingDto.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
                    } else {
                        tempFullBookingDto.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
                    }
                    baseTodayFullBookingList.add(tempFullBookingDto);
                }
                todayBookingList = new BookingListModel(baseTodayFullBookingList);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return baseTodayFullBookingList == null ? new BookingListModel(new ArrayList<FullBookingDto>())
                : todayBookingList;
    }

    // For selecting row
    public FullBookingDto getSelectedBooking() {
        return selectedBooking;
    }

    public void setSelectedBooking(FullBookingDto selectedBooking) {
        this.selectedBooking = selectedBooking;
    }

    // For selecting row
    public FullBookingDto getSelectedTodayBooking() {
        return selectedTodayBooking;
    }

    public void setSelectedTodayBooking(FullBookingDto selectedTodayBooking) {
        this.selectedTodayBooking = selectedTodayBooking;
    }

    // For selecting row
    public FullBookingDto getReassignBooking() {
        return reassignBooking;
    }

    public void setReassignBooking(FullBookingDto reassignBooking) {
        this.reassignBooking = reassignBooking;
    }

    // For selecting row
    public FullCarDto getReassignCar() {
        return reassignCar;
    }

    public void setReassignCar(FullCarDto reassignCar) {
        this.reassignCar = reassignCar;
    }

    public FullBookingDto getEditBooking() {
        return editBooking;
    }

    public void setEditBooking(FullBookingDto editBooking) {
        this.editBooking = editBooking;
    }

    public FullBookingDto getEditTodayBooking() {
        return editTodayBooking;
    }

    public void setEditTodayBooking(FullBookingDto editTodayBooking) {
        this.editTodayBooking = editTodayBooking;
    }

    // For filtering bookings
    public List<FullBookingDto> getFilteredBookings() {
        return filteredBookings;
    }

    public void setFilteredBookings(List<FullBookingDto> filteredBookings) {
        if (filteredBookings == null) {
            this.filteredBookings = filteredBookings;
            return;
        }
        filterByDate();
        this.filteredBookings.retainAll(filteredBookings);
    }

    public void filterByDate() {
        filteredBookings = new ArrayList<FullBookingDto>();
        if (filterStartDate == null) {
            filteredBookings.addAll(baseFullBookingList);
            return;
        }

        // Filter
        for (FullBookingDto bdto : baseFullBookingList) {
            if (getZeroTimeDate(bdto.getStartDate()).compareTo(getZeroTimeDate(filterStartDate)) >= 0) {
                filteredBookings.add(bdto);
            }
        }
    }

    public void onStartDateSelect(DateSelectEvent event) {
        filterStartDate = event.getDate();
    }

    // For filtering bookings
    public List<FullBookingDto> getFilteredTodayBookings() {
        return filteredTodayBookings;
    }

    public void setFilteredTodayBookings(List<FullBookingDto> filteredTodayBookings) {
        this.filteredTodayBookings = filteredTodayBookings;
    }

    // For filtering bookings
    public List<FullBookingDto> getFilteredReassignBookings() {
        return filteredReassignBookings;
    }

    public void setFilteredReassignBookings(List<FullBookingDto> filteredReassignBookings) {
        this.filteredReassignBookings = filteredReassignBookings;
    }

    // For filtering cars
    public List<FullCarDto> getFilteredReassignCars() {
        return filteredReassignCars;
    }

    public void setFilteredReassignCars(List<FullCarDto> filteredReassignCars) {
        this.filteredReassignCars = filteredReassignCars;
    }

    public void deleteBooking() throws IOException {
        try {
            bookingService.deleteBooking(selectedBooking.getId());

            int index = findBookingData(selectedBooking.getId());
            if (index >= 0) {
                baseFullBookingList.remove(index);
            }

            // Update the other table
            index = findTodayBookingData(selectedBooking.getId());
            if (index >= 0) {
                baseTodayFullBookingList.remove(index);
            }
        } catch (IOException e) {
            logger.error("Delete customer error.", e);
            sessionManager.addGlobalMessageFatal("Delete customer error.", null);
            throw e;
        }
    }

    private int findBookingData(int id) {
        for (int i = 0; i < baseFullBookingList.size(); i++) {
            FullBookingDto fullBookingDto = baseFullBookingList.get(i);
            if (fullBookingDto.getId() == id) {
                return i;
            }
        }
        return -1;
    }

    public void deleteTodayBooking() throws IOException {
        try {
            bookingService.deleteBooking(selectedTodayBooking.getId());

            int index = findTodayBookingData(selectedTodayBooking.getId());
            if (index >= 0) {
                baseTodayFullBookingList.remove(index);
            }

            // Update the other table
            index = findBookingData(selectedTodayBooking.getId());
            if (index >= 0) {
                baseFullBookingList.remove(index);
            }
        } catch (IOException e) {
            logger.error("Delete booking error.", e);
            sessionManager.addGlobalMessageFatal("Delete booking error.", null);
            throw e;
        }
    }

    private int findTodayBookingData(int id) {
        for (int i = 0; i < baseTodayFullBookingList.size(); i++) {
            FullBookingDto fullBookingDto = baseTodayFullBookingList.get(i);
            if (fullBookingDto.getId() == id) {
                return i;
            }
        }
        return -1;
    }

    public void startReassign() {
        if (validateFail) {
            return;
        }

        if (editMode) {
            if (editBooking.getStartDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_START_DATE"), null));
                return;
            }
            if (editBooking.getEndDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_END_DATE"), null));
                return;
            }
            if (editBooking.getStartDate().compareTo(editBooking.getEndDate()) >= 0) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("END_DATE_MUST_BE_AFTER_START_DATE"),
                                null));
                return;
            }

            oldDriverId = editBooking.getDriverId();
            if ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0) && driverOn) {
                UserDto freeDriver;
                try {
                    freeDriver = userService.getFreeDriver(editBooking.getStartDate(), editBooking.getEndDate(),
                            currentStoreId);
                    if (freeDriver == null) {
                        FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("ALL_DRIVER_ARE_BUSY"), null));
                        return;
                    }

                    oldDriverId = "";
                    editBooking.setDriverId(freeDriver.getId());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else if (editBooking.getDriverId() != null && editBooking.getDriverId().compareTo("") != 0
                    && !driverOn) {
                oldDriverId = editBooking.getDriverId();
                editBooking.setDriverId("");
            }

            try {
                CarDto currentCar;
                currentCar = carService.getCarById(editBooking.getCarId());

                baseCurrentUsingCar.clear();
                baseCurrentUsingCar.add(currentCar);

                double newPrice;

                if (!driverOn) {
                    newPrice = currentCar.getPriceNoDriver()
                            * (int) ((editBooking.getEndDate().getTime() - editBooking.getStartDate().getTime())
                                    / (1000 * 60 * 60 * 24));
                } else {
                    newPrice = currentCar.getPriceWithDriver()
                            * (int) ((editBooking.getEndDate().getTime() - editBooking.getStartDate().getTime())
                                    / (1000 * 60 * 60 * 24));
                }

                if (currentCar.getCurrency().compareTo(editBooking.getCurrency()) != 0) {
                    if (currencyMap.containsKey(currentCar.getCurrency() + editBooking.getCurrency())) {
                        newPrice = newPrice * currencyMap.get(currentCar.getCurrency() + editBooking.getCurrency());
                    } else {
                        newPrice = newPrice * currencyMap.get(currentCar.getCurrency() + "USD")
                                * currencyMap.get("USD" + editBooking.getCurrency());
                    }
                }
                // Rounding
                newPrice = (double) Math.round(newPrice * 100) / 100;

                oldTotalPrice = editBooking.getTotalPrice();
                editBooking.setTotalPrice(newPrice);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (todayEditMode) {
            if (editTodayBooking.getStartDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_START_DATE"), null));
                return;
            }
            if (editTodayBooking.getEndDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_END_DATE"), null));
                return;
            }
            if (editTodayBooking.getStartDate().compareTo(editTodayBooking.getEndDate()) >= 0) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("END_DATE_MUST_BE_AFTER_START_DATE"),
                                null));
                return;
            }

            oldDriverId = editTodayBooking.getDriverId();
            if ((editTodayBooking.getDriverId() == null || editTodayBooking.getDriverId().compareTo("") == 0)
                    && driverOn) {
                UserDto freeDriver;
                try {
                    freeDriver = userService.getFreeDriver(editTodayBooking.getStartDate(),
                            editTodayBooking.getEndDate(), currentStoreId);
                    if (freeDriver == null) {
                        FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("ALL_DRIVER_ARE_BUSY"), null));
                        return;
                    }

                    oldDriverId = "";
                    editTodayBooking.setDriverId(freeDriver.getId());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } else if (editTodayBooking.getDriverId() != null && editTodayBooking.getDriverId().compareTo("") != 0
                    && !driverOn) {
                oldDriverId = editTodayBooking.getDriverId();
                editTodayBooking.setDriverId("");
            }

            try {
                CarDto currentCar;
                currentCar = carService.getCarById(editTodayBooking.getCarId());

                baseCurrentUsingCar.clear();
                baseCurrentUsingCar.add(currentCar);

                double newPrice;

                if (!driverOn) {
                    newPrice = currentCar.getPriceNoDriver() * (int) ((editTodayBooking.getEndDate().getTime()
                            - editTodayBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                } else {
                    newPrice = currentCar.getPriceWithDriver() * (int) ((editTodayBooking.getEndDate().getTime()
                            - editTodayBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                }

                if (currentCar.getCurrency().compareTo(editTodayBooking.getCurrency()) != 0) {
                    if (currencyMap.containsKey(currentCar.getCurrency() + editTodayBooking.getCurrency())) {
                        newPrice = newPrice
                                * currencyMap.get(currentCar.getCurrency() + editTodayBooking.getCurrency());
                    } else {
                        newPrice = newPrice * currencyMap.get(currentCar.getCurrency() + "USD")
                                * currencyMap.get("USD" + editTodayBooking.getCurrency());
                    }
                }
                // Rounding
                newPrice = (double) Math.round(newPrice * 100) / 100;

                oldTotalPrice = editTodayBooking.getTotalPrice();
                editTodayBooking.setTotalPrice(newPrice);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        reassignMode = true;

        baseFullReassignBookingList.clear();

        boolean flag1, flag2, flag3;

        if (editMode) {
            for (int i = 0; i < baseFullBookingList.size(); i++) {
                FullBookingDto fullBookingDto = baseFullBookingList.get(i);
                if (fullBookingDto.getId() == editBooking.getId()) {
                    reassignBooking = fullBookingDto;
                    baseFullReassignBookingList.add(fullBookingDto);
                    //reassignPage = i;
                    break;
                }
            }

            flag1 = false;
            flag2 = false;
            flag3 = false;

            for (int i = 0; i < conflictBookingList.size(); i++) {
                if (conflictBookingList.get(i).getSecond().intValue() == 1) {
                    flag1 = true;
                    if (flag2) {
                        break;
                    }
                } else if (conflictBookingList.get(0).getSecond().intValue() == 2) {
                    flag2 = true;
                    if (flag1) {
                        break;
                    }
                } else {
                    flag3 = true;
                    break;

                }
            }

            if (flag3 || (flag1 && flag2)) {
                selectedParameters = new int[] { 1, 2 };
            } else if (flag1) {
                selectedParameters = new int[] { 1 };
            } else if (flag2) {
                selectedParameters = new int[] { 2 };
            } else {
                selectedParameters = new int[0];
            }
        } else if (todayEditMode) {
            for (int i = 0; i < baseTodayFullBookingList.size(); i++) {
                FullBookingDto fullBookingDto = baseTodayFullBookingList.get(i);
                if (fullBookingDto.getId() == editTodayBooking.getId()) {
                    reassignBooking = fullBookingDto;
                    baseFullReassignBookingList.add(fullBookingDto);
                    //reassignPage = i;
                    break;
                }
            }

            flag1 = false;
            flag2 = false;
            flag3 = false;

            for (int i = 0; i < conflictBookingList.size(); i++) {
                if (conflictBookingList.get(i).getSecond().intValue() == 1) {
                    flag1 = true;
                    if (flag2) {
                        break;
                    }
                } else if (conflictBookingList.get(0).getSecond().intValue() == 2) {
                    flag2 = true;
                    if (flag1) {
                        break;
                    }
                } else {
                    flag3 = true;
                    break;

                }
            }

            if (flag3 || (flag1 && flag2)) {
                selectedParameters = new int[] { 1, 2 };
            } else if (flag1) {
                selectedParameters = new int[] { 1 };
            } else if (flag2) {
                selectedParameters = new int[] { 2 };
            } else {
                selectedParameters = new int[0];
            }
        } else {
            reassignBooking = null;
            selectedParameters = new int[0];
            reassignPage = 0;
        }

        /*
        Dialog dialog = (Dialog) FacesContext.getCurrentInstance().getViewRoot()
         .findComponent("formReassign:reassignDialog");
        List<UIComponent> dialogChildrenList = dialog.getChildren();
        for (int i = 0; i < dialogChildrenList.size(); i++) {
           UIComponent component1 = dialogChildrenList.get(i);
           if (component1 instanceof DataTable) {
        DataTable d = (DataTable) component1;
        d.setFirst(reassignPage);
        break;
           }
        } // end of for()
        */
    }

    public void startResolveConflict() {
        reassignMode = true;
        resolveConflictMode = true;

        baseFullReassignBookingList.clear();

        if (conflictBookingList.size() > 0) {
            for (int i = 0; i < baseFullBookingList.size(); i++) {
                FullBookingDto fullBookingDto = baseFullBookingList.get(i);
                if (fullBookingDto.getId() == conflictBookingList.get(0).getFirst()) {
                    reassignBooking = fullBookingDto;
                    baseFullReassignBookingList.add(fullBookingDto);
                    break;
                }
            }

            if (conflictBookingList.get(0).getSecond().intValue() == 1) {
                selectedParameters = new int[] { 1 };
            } else if (conflictBookingList.get(0).getSecond().intValue() == 2) {
                selectedParameters = new int[] { 2 };
            } else {
                selectedParameters = new int[] { 1, 2 };
            }
        } else {
            reassignBooking = null;
            selectedParameters = new int[0];
            reassignPage = 0;
        }
    }

    public void startCheck() {
        if (reassignBooking == null) {
            FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            dictionaryController.getDictionary().get("PLEASE_SELECT_A_BOOKING"), null));
            afterCheck = false;
            carReassign = false;
            return;
        }
        if (selectedParameters.length == 0) {
            FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            dictionaryController.getDictionary().get("PLEASE_SELECT_AT_LEAST_CAR_OR_DRIVER"),
                            null));
            afterCheck = false;
            carReassign = false;
            return;
        }

        try {
            baseCarList.clear();
            reassignCar = null;
            double totalPrice;

            if (selectedParameters.length == 1) {
                if (selectedParameters[0] == 1) {// change car
                    List<CarDto> potentialCars;

                    Vector<Fourth<String, String, Double, Double>> carCollection = new Vector<Fourth<String, String, Double, Double>>();
                    boolean breakFlag;
                    Fourth<String, String, Double, Double> fourth;

                    potentialCars = carService.getGoodCarsInStore(currentStoreId);
                    for (int j = 0; j < potentialCars.size(); j++) {
                        if (potentialCars.get(j).getId() == reassignBooking.getCarId()) {
                            continue;
                        }

                        breakFlag = false;
                        for (int k = 0; k < carCollection.size(); k++) {
                            fourth = carCollection.get(k);
                            if (potentialCars.get(j).getBrand().compareTo(fourth.getFirst()) == 0
                                    && potentialCars.get(j).getModel().compareTo(fourth.getSecond()) == 0
                                    && Math.abs(potentialCars.get(j).getPriceNoDriver()
                                            - fourth.getThird().doubleValue()) < 0.1
                                    && Math.abs(potentialCars.get(j).getPriceWithDriver()
                                            - fourth.getFourth().doubleValue()) < 0.1) {
                                breakFlag = true;
                                break;
                            }
                        }

                        if (breakFlag) {
                            continue;
                        }

                        if (bookingService.isCarAvailable(potentialCars.get(j), reassignBooking.getStartDate(),
                                reassignBooking.getEndDate())) {
                            //reassignCarId = potentialCars.get(j).getId();
                            //break;

                            // Check if the car is available or not because of previous Customer return late
                            if (getZeroTimeDate(reassignBooking.getStartDate())
                                    .compareTo(getZeroTimeDate(new Date())) <= 0) {
                                if (bookingService.isCarReturnedLate(potentialCars.get(j).getId(),
                                        getZeroTimeDate(new Date()))) {
                                    continue;
                                }
                            }

                            if (reassignBooking.getDriverId() != null
                                    && reassignBooking.getDriverId().compareTo("") != 0) {
                                totalPrice = potentialCars.get(j).getPriceWithDriver()
                                        * (int) ((reassignBooking.getEndDate().getTime()
                                                - reassignBooking.getStartDate().getTime())
                                                / (1000 * 60 * 60 * 24));
                                if (potentialCars.get(j).getCurrency()
                                        .compareTo(reassignBooking.getCurrency()) != 0) {
                                    if (currencyMap.containsKey(
                                            potentialCars.get(j).getCurrency() + reassignBooking.getCurrency())) {
                                        totalPrice = totalPrice * currencyMap.get(
                                                potentialCars.get(j).getCurrency() + reassignBooking.getCurrency());
                                    } else {
                                        totalPrice = totalPrice
                                                * currencyMap.get(potentialCars.get(j).getCurrency() + "USD")
                                                * currencyMap.get("USD" + reassignBooking.getCurrency());
                                    }
                                }
                            } else {
                                totalPrice = potentialCars.get(j).getPriceNoDriver()
                                        * (int) ((reassignBooking.getEndDate().getTime()
                                                - reassignBooking.getStartDate().getTime())
                                                / (1000 * 60 * 60 * 24));
                                if (potentialCars.get(j).getCurrency()
                                        .compareTo(reassignBooking.getCurrency()) != 0) {
                                    if (currencyMap.containsKey(
                                            potentialCars.get(j).getCurrency() + reassignBooking.getCurrency())) {
                                        totalPrice = totalPrice * currencyMap.get(
                                                potentialCars.get(j).getCurrency() + reassignBooking.getCurrency());
                                    } else {
                                        totalPrice = totalPrice
                                                * currencyMap.get(potentialCars.get(j).getCurrency() + "USD")
                                                * currencyMap.get("USD" + reassignBooking.getCurrency());
                                    }
                                }
                            }

                            // Rounding
                            totalPrice = (double) Math.round(totalPrice * 100) / 100;
                            baseCarList.add(new FullCarDto(potentialCars.get(j).getId(),
                                    potentialCars.get(j).getStoreId(), potentialCars.get(j).getPlateNumber(),
                                    potentialCars.get(j).getBrand(), potentialCars.get(j).getModel(),
                                    potentialCars.get(j).getCapacity(), potentialCars.get(j).getDescription(),
                                    potentialCars.get(j).getPriceNoDriver(),
                                    potentialCars.get(j).getPriceWithDriver(),
                                    potentialCars.get(j).getPriceOverdue(), potentialCars.get(j).getImageSource(),
                                    potentialCars.get(j).getStatus(), totalPrice, reassignBooking.getDriverId(),
                                    reassignBooking.getCurrency()));
                            carCollection.add(new Fourth<String, String, Double, Double>(
                                    potentialCars.get(j).getBrand(), potentialCars.get(j).getModel(),
                                    new Double(potentialCars.get(j).getPriceNoDriver()),
                                    new Double(potentialCars.get(j).getPriceWithDriver())));
                        }
                    }

                    //if(reassignCarId>0){
                    if (baseCarList.size() > 0) {
                        //FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("AVAILABLE") + ": " + dictionaryController.getDictionary().get("Car ID") + ": " + String.valueOf(reassignCarId), null));
                        afterCheck = true;
                        carReassign = true;
                        return;
                    } else {
                        FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                                new FacesMessage(FacesMessage.SEVERITY_INFO,
                                        dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
                        afterCheck = false;
                        carReassign = false;
                        return;
                    }
                } else if (selectedParameters[0] == 2) { // change driver
                    if (reassignBooking.getDriverId() != null && reassignBooking.getDriverId().compareTo("") != 0) {
                        UserDto freeDriver = userService.getFreeDriver(reassignBooking.getStartDate(),
                                reassignBooking.getEndDate(), currentStoreId);

                        if (freeDriver != null) {
                            reassignDriverId = freeDriver.getId();
                            FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                                            dictionaryController.getDictionary().get("AVAILABLE") + ": "
                                                    + dictionaryController.getDictionary().get("Driver ID") + ": "
                                                    + reassignDriverId,
                                            null));
                            afterCheck = true;
                            carReassign = false;
                            return;
                        } else {
                            FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                                    new FacesMessage(FacesMessage.SEVERITY_INFO,
                                            dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
                            afterCheck = false;
                            carReassign = false;
                            return;
                        }
                    } else {
                        FacesContext.getCurrentInstance()
                                .addMessage("messageReassignDialog",
                                        new FacesMessage(FacesMessage.SEVERITY_INFO, dictionaryController
                                                .getDictionary().get("THIS_BOOKING_DOES_NOT_REQUIRE_DRIVER"),
                                                null));
                        afterCheck = false;
                        carReassign = false;
                        return;
                    }
                }
            } else { // change both
                List<CarDto> potentialCars;

                Vector<Fourth<String, String, Double, Double>> carCollection = new Vector<Fourth<String, String, Double, Double>>();
                boolean breakFlag;
                Fourth<String, String, Double, Double> fourth;

                potentialCars = carService.getGoodCarsInStore(currentStoreId);
                for (int j = 0; j < potentialCars.size(); j++) {
                    if (potentialCars.get(j).getId() == reassignBooking.getCarId()) {
                        continue;
                    }

                    breakFlag = false;
                    for (int k = 0; k < carCollection.size(); k++) {
                        fourth = carCollection.get(k);
                        if (potentialCars.get(j).getBrand().compareTo(fourth.getFirst()) == 0
                                && potentialCars.get(j).getModel().compareTo(fourth.getSecond()) == 0
                                && Math.abs(potentialCars.get(j).getPriceNoDriver()
                                        - fourth.getThird().doubleValue()) < 0.1
                                && Math.abs(potentialCars.get(j).getPriceWithDriver()
                                        - fourth.getFourth().doubleValue()) < 0.1) {
                            breakFlag = true;
                            break;
                        }
                    }

                    if (breakFlag) {
                        continue;
                    }

                    if (bookingService.isCarAvailable(potentialCars.get(j), reassignBooking.getStartDate(),
                            reassignBooking.getEndDate())) {
                        //reassignCarId = potentialCars.get(j).getId();
                        //break;

                        // Check if the car is available or not because of previous Customer return late
                        if (getZeroTimeDate(reassignBooking.getStartDate())
                                .compareTo(getZeroTimeDate(new Date())) <= 0) {
                            if (bookingService.isCarReturnedLate(potentialCars.get(j).getId(),
                                    getZeroTimeDate(new Date()))) {
                                continue;
                            }
                        }

                        if (reassignBooking.getDriverId() != null
                                && reassignBooking.getDriverId().compareTo("") != 0) {
                            totalPrice = potentialCars.get(j).getPriceWithDriver()
                                    * (int) ((reassignBooking.getEndDate().getTime()
                                            - reassignBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                            if (potentialCars.get(j).getCurrency().compareTo(reassignBooking.getCurrency()) != 0) {
                                if (currencyMap.containsKey(
                                        potentialCars.get(j).getCurrency() + reassignBooking.getCurrency())) {
                                    totalPrice = totalPrice * currencyMap.get(
                                            potentialCars.get(j).getCurrency() + reassignBooking.getCurrency());
                                } else {
                                    totalPrice = totalPrice
                                            * currencyMap.get(potentialCars.get(j).getCurrency() + "USD")
                                            * currencyMap.get("USD" + reassignBooking.getCurrency());
                                }
                            }
                        } else {
                            totalPrice = potentialCars.get(j).getPriceNoDriver()
                                    * (int) ((reassignBooking.getEndDate().getTime()
                                            - reassignBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                            if (potentialCars.get(j).getCurrency().compareTo(reassignBooking.getCurrency()) != 0) {
                                if (currencyMap.containsKey(
                                        potentialCars.get(j).getCurrency() + reassignBooking.getCurrency())) {
                                    totalPrice = totalPrice * currencyMap.get(
                                            potentialCars.get(j).getCurrency() + reassignBooking.getCurrency());
                                } else {
                                    totalPrice = totalPrice
                                            * currencyMap.get(potentialCars.get(j).getCurrency() + "USD")
                                            * currencyMap.get("USD" + reassignBooking.getCurrency());
                                }
                            }
                        }

                        // Rounding
                        totalPrice = (double) Math.round(totalPrice * 100) / 100;
                        baseCarList.add(new FullCarDto(potentialCars.get(j).getId(),
                                potentialCars.get(j).getStoreId(), potentialCars.get(j).getPlateNumber(),
                                potentialCars.get(j).getBrand(), potentialCars.get(j).getModel(),
                                potentialCars.get(j).getCapacity(), potentialCars.get(j).getDescription(),
                                potentialCars.get(j).getPriceNoDriver(), potentialCars.get(j).getPriceWithDriver(),
                                potentialCars.get(j).getPriceOverdue(), potentialCars.get(j).getImageSource(),
                                potentialCars.get(j).getStatus(), totalPrice, reassignBooking.getDriverId(),
                                reassignBooking.getCurrency()));
                        carCollection.add(new Fourth<String, String, Double, Double>(
                                potentialCars.get(j).getBrand(), potentialCars.get(j).getModel(),
                                new Double(potentialCars.get(j).getPriceNoDriver()),
                                new Double(potentialCars.get(j).getPriceWithDriver())));
                    }
                }

                //if(reassignCarId<0){
                if (baseCarList.size() <= 0) {
                    FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                            new FacesMessage(FacesMessage.SEVERITY_INFO,
                                    dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
                    afterCheck = false;
                    carReassign = false;
                    return;
                }

                if (reassignBooking.getDriverId() != null && reassignBooking.getDriverId().compareTo("") != 0) {
                    UserDto freeDriver = userService.getFreeDriver(reassignBooking.getStartDate(),
                            reassignBooking.getEndDate(), currentStoreId);

                    if (freeDriver != null) {
                        reassignDriverId = freeDriver.getId();
                        //FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("AVAILABLE") + ": " + dictionaryController.getDictionary().get("Car ID") + ": " + String.valueOf(reassignCarId) + ", " + dictionaryController.getDictionary().get("Driver ID") + ": " + reassignDriverId, null));
                        FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                                new FacesMessage(FacesMessage.SEVERITY_INFO,
                                        dictionaryController.getDictionary().get("AVAILABLE") + ": "
                                                + dictionaryController.getDictionary().get("Driver ID") + ": "
                                                + reassignDriverId,
                                        null));
                        afterCheck = true;
                        carReassign = true;
                        return;
                    } else {
                        FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                                new FacesMessage(FacesMessage.SEVERITY_INFO,
                                        dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
                        afterCheck = false;
                        carReassign = false;
                        return;
                    }
                } else {
                    //FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("AVAILABLE") + ": " + dictionaryController.getDictionary().get("Car ID") + ": " + String.valueOf(reassignCarId) + ", " + dictionaryController.getDictionary().get("Driver ID") + ": " + reassignDriverId, null));
                    afterCheck = true;
                    carReassign = true;
                    return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startReassignApply() {
        /*
        if (reassignBooking == null){
           FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_ERROR, dictionaryController.getDictionary().get("PLEASE_SELECT_A_BOOKING"), null));
           return;
        }
        if(selectedParameters.length == 0){
           FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_ERROR, dictionaryController.getDictionary().get("PLEASE_SELECT_AT_LEAST_CAR_OR_DRIVER"), null));
           return;
        }
        */

        if (selectedParameters.length == 1) {
            if (selectedParameters[0] == 1) {// change car
                /*
                List<CarDto> potentialCars;
                potentialCars = carService.getGoodCarsInStore(currentStoreId);
                for (int j = 0; j<potentialCars.size(); j++){
                   if(potentialCars.get(j).getId() == reassignBooking.getCarId()){
                 continue;
                   }
                   if (bookingService.isCarAvailable(potentialCars.get(j), reassignBooking.getStartDate(), reassignBooking.getEndDate())){
                 reassignCarId = potentialCars.get(j).getId();
                 break;
                   }
                }
                    
                if(reassignCarId<0){
                   FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_WARN, dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
                   return;
                }
                */

                if (reassignCar == null) {
                    FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                    dictionaryController.getDictionary().get("PLEASE_SELECT_A_CAR"), null));
                    return;
                }

                reassignCarId = reassignCar.getId();

                // Retrieve old value for displaying
                reassignDriverId = reassignBooking.getDriverId();
            } else if (selectedParameters[0] == 2) { // change driver
                /*
                if(reassignBooking.getDriverId()!= null && reassignBooking.getDriverId().compareTo("") != 0){
                   UserDto freeDriver = userService.getFreeDriver(reassignBooking.getStartDate(), reassignBooking.getEndDate(), currentStoreId);
                    
                   if(freeDriver == null){
                 FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_WARN, dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
                 return;
                   }
                   reassignDriverId = freeDriver.getId();
                } else{
                   FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_WARN, dictionaryController.getDictionary().get("THIS_BOOKING_DOES_NOT_REQUIRE_DRIVER"), null));
                   return;
                }
                */

                // Retrieve old value for displaying
                reassignCarId = reassignBooking.getCarId();
            }
        } else { // change both
            /*
            List<CarDto> potentialCars;
            potentialCars = carService.getGoodCarsInStore(currentStoreId);
                
            for (int j = 0; j<potentialCars.size(); j++){
               if(potentialCars.get(j).getId() == reassignBooking.getCarId()){
              continue;
               }
               if (bookingService.isCarAvailable(potentialCars.get(j), reassignBooking.getStartDate(), reassignBooking.getEndDate())){
              reassignCarId = potentialCars.get(j).getId();
              break;
               }
            }
                
            if(reassignCarId<0){
               FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_WARN, dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
               return;
            }
            */

            if (reassignCar == null) {
                FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_A_CAR"), null));
                return;
            }

            reassignCarId = reassignCar.getId();

            /*
            if(reassignBooking.getDriverId()!= null && reassignBooking.getDriverId().compareTo("") != 0){
               UserDto freeDriver = userService.getFreeDriver(reassignBooking.getStartDate(), reassignBooking.getEndDate(), currentStoreId);
                
               if(freeDriver == null){
              FacesContext.getCurrentInstance().addMessage("messageReassignDialog", new FacesMessage(FacesMessage.SEVERITY_WARN, dictionaryController.getDictionary().get("CANNOT_REASSIGN"), null));
              return;
               }
               reassignDriverId = freeDriver.getId();
            }
            */
        }

        // Show confirm dialog
        RequestContext.getCurrentInstance().execute("reassignConfirmDialog_w.show()");
    }

    public void startEdit() throws IOException {
        editBooking = selectedBooking;
        editMode = true;

        startDateToRestore = editBooking.getStartDate();
        endDateToRestore = editBooking.getEndDate();
        statusToRestore = editBooking.getStatus();
        remindRemarkToRestore = editBooking.getRemindRemark();
        returnRemarkToRestore = editBooking.getReturnRemark();
        oldDamageCharge = editBooking.getDamageCharge();

        if (editBooking != null && editBooking.getDriverId() != null
                && editBooking.getDriverId().compareTo("") != 0) {
            driverOn = true;
        } else {
            driverOn = false;
        }
    }

    public void startReturnCar() throws IOException {
        editBooking = selectedBooking;
        editMode = true;

        startDateToRestore = editBooking.getStartDate();
        endDateToRestore = editBooking.getEndDate();
        statusToRestore = editBooking.getStatus();
        remindRemarkToRestore = editBooking.getRemindRemark();
        returnRemarkToRestore = editBooking.getReturnRemark();
        oldDamageCharge = editBooking.getDamageCharge();

        if (editBooking != null && editBooking.getDriverId() != null
                && editBooking.getDriverId().compareTo("") != 0) {
            driverOn = true;
        } else {
            driverOn = false;
        }

        returnCarMode = true;
    }

    public void startTodayEdit() throws IOException {
        editTodayBooking = selectedTodayBooking;
        todayEditMode = true;

        startDateToRestore = editTodayBooking.getStartDate();
        endDateToRestore = editTodayBooking.getEndDate();
        statusToRestore = editTodayBooking.getStatus();
        remindRemarkToRestore = editTodayBooking.getRemindRemark();
        returnRemarkToRestore = editTodayBooking.getReturnRemark();
        oldDamageCharge = editTodayBooking.getDamageCharge();

        if (editTodayBooking != null && editTodayBooking.getDriverId() != null
                && editTodayBooking.getDriverId().compareTo("") != 0) {
            driverOn = true;
        } else {
            driverOn = false;
        }
    }

    public void startTodayReturnCar() throws IOException {
        editTodayBooking = selectedTodayBooking;
        todayEditMode = true;

        startDateToRestore = editTodayBooking.getStartDate();
        endDateToRestore = editTodayBooking.getEndDate();
        statusToRestore = editTodayBooking.getStatus();
        remindRemarkToRestore = editTodayBooking.getRemindRemark();
        returnRemarkToRestore = editTodayBooking.getReturnRemark();
        oldDamageCharge = editTodayBooking.getDamageCharge();

        if (editTodayBooking != null && editTodayBooking.getDriverId() != null
                && editTodayBooking.getDriverId().compareTo("") != 0) {
            driverOn = true;
        } else {
            driverOn = false;
        }

        returnCarMode = true;
    }

    public void startApply() {
        try {
            sendCarForMaintenance = false;

            if (editBooking.getStartDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_START_DATE"), null));
                return;
            }
            if (editBooking.getEndDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_END_DATE"), null));
                return;
            }
            if (editBooking.getStartDate().compareTo(editBooking.getEndDate()) >= 0 && !returnCarMode) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("END_DATE_MUST_BE_AFTER_START_DATE"),
                                null));
                return;
            }

            if (returnCarMode) {
                editBooking.setEndDate(getZeroTimeDate(new Date()));
            }

            if ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0) && driverOn) {
                UserDto freeDriver = userService.getFreeDriver(editBooking.getStartDate(), editBooking.getEndDate(),
                        currentStoreId);

                if (freeDriver == null) {
                    FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                    dictionaryController.getDictionary().get("ALL_DRIVER_ARE_BUSY"), null));
                    return;
                }

                changeDriverId = freeDriver.getId();
            } else if (editBooking.getDriverId() != null && editBooking.getDriverId().compareTo("") != 0
                    && !driverOn) {
                changeDriverId = "";
            }

            if (!returnCarMode && editBooking.getStatus().compareTo("SERVING") != 0) {
                conflictBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                        .getConflictBookingList(editBooking);
                if (conflictBookingList.size() > 0) {
                    String str = "";
                    for (int i = 0; i < conflictBookingList.size() - 1; i++) {
                        str = str + String.valueOf(conflictBookingList.get(i).getFirst()) + ", ";
                    }
                    str = str + String.valueOf(conflictBookingList.get(conflictBookingList.size() - 1).getFirst());

                    FacesContext.getCurrentInstance()
                            .addMessage("messageDetailDialog",
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, dictionaryController
                                            .getDictionary().get("CANNOT_EDIT_CONFLICT_WITH_BOOKINGS") + ": " + str,
                                            null));
                    return;
                }

                // Check if the car is available or not because of previous Customer return late
                if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) <= 0) {
                    boolean carLate = false;
                    boolean driverLate = false;

                    if (bookingService.isCarReturnedLate(editBooking.getCarId(), getZeroTimeDate(new Date()))) {
                        carLate = true;
                    }

                    if ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0)
                            && driverOn) {
                        if (bookingService.isDriverReturnedLate(changeDriverId, getZeroTimeDate(new Date()))) {
                            driverLate = true;
                        }
                    } else if (driverOn) {
                        if (bookingService.isDriverReturnedLate(editBooking.getDriverId(),
                                getZeroTimeDate(new Date()))) {
                            driverLate = true;
                        }
                    }

                    if (carLate && driverLate) {
                        FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("CAR_AND_DRIVER_IS_NOT_AVAILABLE"),
                                        null));
                        return;
                    } else if (carLate) {
                        FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("CAR_IS_NOT_AVAILABLE"), null));
                        return;
                    } else if (driverLate) {
                        FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("DRIVER_IS_NOT_AVAILABLE"), null));
                        return;
                    }
                }
            }

            if ((getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(startDateToRestore)) == 0
                    && getZeroTimeDate(editBooking.getEndDate()).compareTo(getZeroTimeDate(endDateToRestore)) == 0)
                    && ((editBooking.getDriverId() != null && editBooking.getDriverId().compareTo("") != 0
                            && driverOn)
                            || ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0)
                                    && !driverOn))) {
                if (Math.abs(oldDamageCharge - editBooking.getDamageCharge()) > 0.01) {
                    newEditPrice = editBooking.getTotalPrice() - oldDamageCharge + editBooking.getDamageCharge();
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                            + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                            + "<br/>" + dictionaryController.getDictionary().get("New price") + ": " + newEditPrice
                            + " (" + editBooking.getCurrency() + ")";
                } else {
                    newEditPrice = editBooking.getTotalPrice();

                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                }
            } else {
                CarDto currentCar;
                currentCar = carService.getCarById(editBooking.getCarId());

                if (returnCarMode && getZeroTimeDate(editBooking.getEndDate())
                        .compareTo(getZeroTimeDate(endDateToRestore)) < 0) {
                    if (Math.abs(oldDamageCharge - editBooking.getDamageCharge()) > 0.01) {
                        newEditPrice = editBooking.getTotalPrice() - oldDamageCharge
                                + editBooking.getDamageCharge();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                                + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                + newEditPrice + " (" + editBooking.getCurrency() + ")";
                    } else {
                        newEditPrice = editBooking.getTotalPrice();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                    }
                } else {
                    if (!driverOn) {
                        newEditPrice = currentCar.getPriceNoDriver()
                                * (int) ((editBooking.getEndDate().getTime() - editBooking.getStartDate().getTime())
                                        / (1000 * 60 * 60 * 24));
                    } else {
                        newEditPrice = currentCar.getPriceWithDriver()
                                * (int) ((editBooking.getEndDate().getTime() - editBooking.getStartDate().getTime())
                                        / (1000 * 60 * 60 * 24));
                    }

                    if (overdueCharge && getZeroTimeDate(editBooking.getEndDate())
                            .compareTo(getZeroTimeDate(endDateToRestore)) > 0) {
                        newEditPrice += currentCar.getPriceOverdue()
                                * (int) ((editBooking.getEndDate().getTime() - endDateToRestore.getTime())
                                        / (1000 * 60 * 60 * 24));
                    }

                    // Add booking adjustment charge
                    newBookingAdjustmentCharge = 0;
                    if (!returnCarMode && editBooking.getStatus().compareTo("SERVING") == 0
                            && getZeroTimeDate(editBooking.getEndDate())
                                    .compareTo(getZeroTimeDate(endDateToRestore)) > 0) {
                        newBookingAdjustmentCharge = currentCar.getPriceOverdue()
                                * (int) ((editBooking.getEndDate().getTime() - endDateToRestore.getTime())
                                        / (1000 * 60 * 60 * 24));
                        newBookingAdjustmentCharge += editBooking.getBookingAdjustmentCharge();
                    }

                    newEditPrice += newBookingAdjustmentCharge;

                    // Add damage charge
                    newEditPrice += editBooking.getDamageCharge();

                    if (currentCar.getCurrency().compareTo(editBooking.getCurrency()) != 0) {
                        if (currencyMap.containsKey(currentCar.getCurrency() + editBooking.getCurrency())) {
                            newEditPrice = newEditPrice
                                    * currencyMap.get(currentCar.getCurrency() + editBooking.getCurrency());
                        } else {
                            newEditPrice = newEditPrice * currencyMap.get(currentCar.getCurrency() + "USD")
                                    * currencyMap.get("USD" + editBooking.getCurrency());
                        }
                    }
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    if (!returnCarMode && editBooking.getStatus().compareTo("SERVING") == 0) {
                        List<Pair<Integer, Integer>> affectedBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                                .getConflictBookingList(editBooking);
                        if (affectedBookingList.size() > 0) {
                            confirmMessage = dictionaryController.getDictionary()
                                    .get("SOME_FUTURE_BOOKINGS_WILL_BE_AFFECTED") + "<br/>" + "<br/>"
                                    + dictionaryController.getDictionary().get("Old price") + ": "
                                    + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                                    + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                    + newEditPrice + " (" + editBooking.getCurrency() + ")";
                        } else {
                            confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                    + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                                    + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                    + newEditPrice + " (" + editBooking.getCurrency() + ")";
                        }
                    } else {
                        confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                                + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                + newEditPrice + " (" + editBooking.getCurrency() + ")";
                    }
                }
            }

            // Show confirm dialog
            RequestContext.getCurrentInstance().execute("applyConfirmDialog_w.show()");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startApplyAndSendCarForMaintenance() {
        try {
            sendCarForMaintenance = true;

            if (editBooking.getStartDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_START_DATE"), null));
                return;
            }
            if (editBooking.getEndDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_END_DATE"), null));
                return;
            }
            if (editBooking.getStartDate().compareTo(editBooking.getEndDate()) >= 0 && !returnCarMode) {
                FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("END_DATE_MUST_BE_AFTER_START_DATE"),
                                null));
                return;
            }

            if (returnCarMode) {
                editBooking.setEndDate(getZeroTimeDate(new Date()));
            }

            if (!returnCarMode) {
                conflictBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                        .getConflictBookingList(editBooking);
                if (conflictBookingList.size() > 0) {
                    String str = "";
                    for (int i = 0; i < conflictBookingList.size() - 1; i++) {
                        str = str + String.valueOf(conflictBookingList.get(i).getFirst()) + ", ";
                    }
                    str = str + String.valueOf(conflictBookingList.get(conflictBookingList.size() - 1).getFirst());

                    FacesContext.getCurrentInstance()
                            .addMessage("messageDetailDialog",
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, dictionaryController
                                            .getDictionary().get("CANNOT_EDIT_CONFLICT_WITH_BOOKINGS") + ": " + str,
                                            null));
                    return;
                }
            }

            if ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0) && driverOn) {
                UserDto freeDriver = userService.getFreeDriver(editBooking.getStartDate(), editBooking.getEndDate(),
                        currentStoreId);

                if (freeDriver == null) {
                    FacesContext.getCurrentInstance().addMessage("messageDetailDialog",
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                    dictionaryController.getDictionary().get("ALL_DRIVER_ARE_BUSY"), null));
                    return;
                }

                changeDriverId = freeDriver.getId();
            } else if (editBooking.getDriverId() != null && editBooking.getDriverId().compareTo("") != 0
                    && !driverOn) {
                changeDriverId = "";
            }

            if ((getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(startDateToRestore)) == 0
                    && getZeroTimeDate(editBooking.getEndDate()).compareTo(getZeroTimeDate(endDateToRestore)) == 0)
                    && ((editBooking.getDriverId() != null && editBooking.getDriverId().compareTo("") != 0
                            && driverOn)
                            || ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0)
                                    && !driverOn))) {
                if (Math.abs(oldDamageCharge - editBooking.getDamageCharge()) > 0.01) {
                    newEditPrice = editBooking.getTotalPrice() - oldDamageCharge + editBooking.getDamageCharge();
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                            + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                            + "<br/>" + dictionaryController.getDictionary().get("New price") + ": " + newEditPrice
                            + " (" + editBooking.getCurrency() + ")";
                } else {
                    newEditPrice = editBooking.getTotalPrice();

                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                }
            } else {
                CarDto currentCar;
                currentCar = carService.getCarById(editBooking.getCarId());

                if (returnCarMode && getZeroTimeDate(editBooking.getEndDate())
                        .compareTo(getZeroTimeDate(endDateToRestore)) < 0) {
                    if (Math.abs(oldDamageCharge - editBooking.getDamageCharge()) > 0.01) {
                        newEditPrice = editBooking.getTotalPrice() - oldDamageCharge
                                + editBooking.getDamageCharge();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                                + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                + newEditPrice + " (" + editBooking.getCurrency() + ")";
                    } else {
                        newEditPrice = editBooking.getTotalPrice();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                    }
                } else {
                    if (!driverOn) {
                        newEditPrice = currentCar.getPriceNoDriver()
                                * (int) ((editBooking.getEndDate().getTime() - editBooking.getStartDate().getTime())
                                        / (1000 * 60 * 60 * 24));
                    } else {
                        newEditPrice = currentCar.getPriceWithDriver()
                                * (int) ((editBooking.getEndDate().getTime() - editBooking.getStartDate().getTime())
                                        / (1000 * 60 * 60 * 24));
                    }

                    if (overdueCharge && getZeroTimeDate(editBooking.getEndDate())
                            .compareTo(getZeroTimeDate(endDateToRestore)) > 0) {
                        newEditPrice += currentCar.getPriceOverdue()
                                * (int) ((editBooking.getEndDate().getTime() - endDateToRestore.getTime())
                                        / (1000 * 60 * 60 * 24));
                    }

                    // Add damage charge
                    newEditPrice += editBooking.getDamageCharge();

                    if (currentCar.getCurrency().compareTo(editBooking.getCurrency()) != 0) {
                        if (currencyMap.containsKey(currentCar.getCurrency() + editBooking.getCurrency())) {
                            newEditPrice = newEditPrice
                                    * currencyMap.get(currentCar.getCurrency() + editBooking.getCurrency());
                        } else {
                            newEditPrice = newEditPrice * currencyMap.get(currentCar.getCurrency() + "USD")
                                    * currencyMap.get("USD" + editBooking.getCurrency());
                        }
                    }
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                            + editBooking.getTotalPrice() + " (" + editBooking.getCurrency() + ")" + "<br/>"
                            + "<br/>" + dictionaryController.getDictionary().get("New price") + ": " + newEditPrice
                            + " (" + editBooking.getCurrency() + ")";
                }
            }

            // Show confirm dialog
            RequestContext.getCurrentInstance().execute("applyConfirmDialog_w.show()");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startTodayApply() {
        try {
            sendCarForMaintenance = false;

            if (editTodayBooking.getStartDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_START_DATE"), null));
                return;
            }
            if (editTodayBooking.getEndDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_END_DATE"), null));
                return;
            }
            if (editTodayBooking.getStartDate().compareTo(editTodayBooking.getEndDate()) >= 0 && !returnCarMode) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("END_DATE_MUST_BE_AFTER_START_DATE"),
                                null));
                return;
            }

            if (returnCarMode) {
                editTodayBooking.setEndDate(getZeroTimeDate(new Date()));
            }

            if ((editTodayBooking.getDriverId() == null || editTodayBooking.getDriverId().compareTo("") == 0)
                    && driverOn) {
                UserDto freeDriver = userService.getFreeDriver(editTodayBooking.getStartDate(),
                        editTodayBooking.getEndDate(), currentStoreId);

                if (freeDriver == null) {
                    FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                    dictionaryController.getDictionary().get("ALL_DRIVER_ARE_BUSY"), null));
                    return;
                }

                changeDriverId = freeDriver.getId();
            } else if (editTodayBooking.getDriverId() != null && editTodayBooking.getDriverId().compareTo("") != 0
                    && !driverOn) {
                changeDriverId = "";
            }

            if (!returnCarMode && editTodayBooking.getStatus().compareTo("SERVING") != 0) {
                conflictBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                        .getConflictBookingList(editTodayBooking);
                if (conflictBookingList.size() > 0) {
                    String str = "";
                    for (int i = 0; i < conflictBookingList.size() - 1; i++) {
                        str = str + String.valueOf(conflictBookingList.get(i).getFirst()) + ", ";
                    }
                    str = str + String.valueOf(conflictBookingList.get(conflictBookingList.size() - 1).getFirst());

                    FacesContext.getCurrentInstance()
                            .addMessage("messageTodayDetailDialog",
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, dictionaryController
                                            .getDictionary().get("CANNOT_EDIT_CONFLICT_WITH_BOOKINGS") + ": " + str,
                                            null));
                    return;
                }

                // Check if the car is available or not because of previous Customer return late
                if (getZeroTimeDate(editTodayBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) <= 0) {
                    boolean carLate = false;
                    boolean driverLate = false;

                    if (bookingService.isCarReturnedLate(editTodayBooking.getCarId(),
                            getZeroTimeDate(new Date()))) {
                        carLate = true;
                    }

                    if ((editTodayBooking.getDriverId() == null
                            || editTodayBooking.getDriverId().compareTo("") == 0) && driverOn) {
                        if (bookingService.isDriverReturnedLate(changeDriverId, getZeroTimeDate(new Date()))) {
                            driverLate = true;
                        }
                    } else if (driverOn) {
                        if (bookingService.isDriverReturnedLate(editTodayBooking.getDriverId(),
                                getZeroTimeDate(new Date()))) {
                            driverLate = true;
                        }
                    }

                    if (carLate && driverLate) {
                        FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("CAR_AND_DRIVER_IS_NOT_AVAILABLE"),
                                        null));
                        return;
                    } else if (carLate) {
                        FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("CAR_IS_NOT_AVAILABLE"), null));
                        return;
                    } else if (driverLate) {
                        FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                        dictionaryController.getDictionary().get("DRIVER_IS_NOT_AVAILABLE"), null));
                        return;
                    }
                }
            }

            if ((getZeroTimeDate(editTodayBooking.getStartDate())
                    .compareTo(getZeroTimeDate(startDateToRestore)) == 0
                    && getZeroTimeDate(editTodayBooking.getEndDate())
                            .compareTo(getZeroTimeDate(endDateToRestore)) == 0)
                    && ((editTodayBooking.getDriverId() != null && editTodayBooking.getDriverId().compareTo("") != 0
                            && driverOn)
                            || ((editTodayBooking.getDriverId() == null
                                    || editTodayBooking.getDriverId().compareTo("") == 0) && !driverOn))) {
                if (Math.abs(oldDamageCharge - editTodayBooking.getDamageCharge()) > 0.01) {
                    newEditPrice = editTodayBooking.getTotalPrice() - oldDamageCharge
                            + editTodayBooking.getDamageCharge();
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;
                    confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                            + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                            + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                            + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                } else {
                    newEditPrice = editTodayBooking.getTotalPrice();
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;
                    confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                }
            } else {
                CarDto currentCar = carService.getCarById(editTodayBooking.getCarId());

                if (returnCarMode && getZeroTimeDate(editTodayBooking.getEndDate())
                        .compareTo(getZeroTimeDate(endDateToRestore)) < 0) {
                    if (Math.abs(oldDamageCharge - editTodayBooking.getDamageCharge()) > 0.01) {
                        newEditPrice = editTodayBooking.getTotalPrice() - oldDamageCharge
                                + editTodayBooking.getDamageCharge();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                                + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                    } else {
                        newEditPrice = editTodayBooking.getTotalPrice();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                    }
                } else {
                    if (!driverOn) {
                        newEditPrice = currentCar.getPriceNoDriver()
                                * (int) ((editTodayBooking.getEndDate().getTime()
                                        - editTodayBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                    } else {
                        newEditPrice = currentCar.getPriceWithDriver()
                                * (int) ((editTodayBooking.getEndDate().getTime()
                                        - editTodayBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                    }

                    if (overdueCharge && getZeroTimeDate(editTodayBooking.getEndDate())
                            .compareTo(getZeroTimeDate(endDateToRestore)) > 0) {
                        newEditPrice += currentCar.getPriceOverdue()
                                * (int) ((editTodayBooking.getEndDate().getTime() - endDateToRestore.getTime())
                                        / (1000 * 60 * 60 * 24));
                    }

                    // Add booking adjustment charge
                    newBookingAdjustmentCharge = 0;
                    if (!returnCarMode && editTodayBooking.getStatus().compareTo("SERVING") == 0
                            && getZeroTimeDate(editTodayBooking.getEndDate())
                                    .compareTo(getZeroTimeDate(endDateToRestore)) > 0) {
                        newBookingAdjustmentCharge = currentCar.getPriceOverdue()
                                * (int) ((editTodayBooking.getEndDate().getTime() - endDateToRestore.getTime())
                                        / (1000 * 60 * 60 * 24));
                        newBookingAdjustmentCharge += editTodayBooking.getBookingAdjustmentCharge();
                    }

                    newEditPrice += newBookingAdjustmentCharge;

                    // Add damage charge
                    newEditPrice += editTodayBooking.getDamageCharge();

                    if (currentCar.getCurrency().compareTo(editTodayBooking.getCurrency()) != 0) {
                        if (currencyMap.containsKey(currentCar.getCurrency() + editTodayBooking.getCurrency())) {
                            newEditPrice = newEditPrice
                                    * currencyMap.get(currentCar.getCurrency() + editTodayBooking.getCurrency());
                        } else {
                            newEditPrice = newEditPrice * currencyMap.get(currentCar.getCurrency() + "USD")
                                    * currencyMap.get("USD" + editTodayBooking.getCurrency());
                        }
                    }
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    if (!returnCarMode && editTodayBooking.getStatus().compareTo("SERVING") == 0) {
                        List<Pair<Integer, Integer>> affectedBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                                .getConflictBookingList(editTodayBooking);
                        if (affectedBookingList.size() > 0) {
                            confirmMessage = dictionaryController.getDictionary()
                                    .get("SOME_FUTURE_BOOKINGS_WILL_BE_AFFECTED") + "<br/>" + "<br/>"
                                    + dictionaryController.getDictionary().get("Old price") + ": "
                                    + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                                    + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price")
                                    + ": " + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                        } else {
                            confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                    + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                                    + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price")
                                    + ": " + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                        }
                    } else {
                        confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                                + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                    }
                }
            }

            // Show confirm dialog
            RequestContext.getCurrentInstance().execute("todayApplyConfirmDialog_w.show()");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startTodayApplyAndSendCarForMaintenance() {
        try {
            sendCarForMaintenance = true;

            if (editTodayBooking.getStartDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_START_DATE"), null));
                return;
            }
            if (editTodayBooking.getEndDate() == null) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("PLEASE_SELECT_END_DATE"), null));
                return;
            }
            if (editTodayBooking.getStartDate().compareTo(editTodayBooking.getEndDate()) >= 0 && !returnCarMode) {
                FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                        new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                dictionaryController.getDictionary().get("END_DATE_MUST_BE_AFTER_START_DATE"),
                                null));
                return;
            }

            if (returnCarMode) {
                editTodayBooking.setEndDate(getZeroTimeDate(new Date()));
            }

            if (!returnCarMode) {
                conflictBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                        .getConflictBookingList(editTodayBooking);
                if (conflictBookingList.size() > 0) {
                    String str = "";
                    for (int i = 0; i < conflictBookingList.size() - 1; i++) {
                        str = str + String.valueOf(conflictBookingList.get(i).getFirst()) + ", ";
                    }
                    str = str + String.valueOf(conflictBookingList.get(conflictBookingList.size() - 1).getFirst());

                    FacesContext.getCurrentInstance()
                            .addMessage("messageTodayDetailDialog",
                                    new FacesMessage(FacesMessage.SEVERITY_ERROR, dictionaryController
                                            .getDictionary().get("CANNOT_EDIT_CONFLICT_WITH_BOOKINGS") + ": " + str,
                                            null));
                    return;
                }
            }

            if ((editTodayBooking.getDriverId() == null || editTodayBooking.getDriverId().compareTo("") == 0)
                    && driverOn) {
                UserDto freeDriver = userService.getFreeDriver(editTodayBooking.getStartDate(),
                        editTodayBooking.getEndDate(), currentStoreId);

                if (freeDriver == null) {
                    FacesContext.getCurrentInstance().addMessage("messageTodayDetailDialog",
                            new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                    dictionaryController.getDictionary().get("ALL_DRIVER_ARE_BUSY"), null));
                    return;
                }

                changeDriverId = freeDriver.getId();
            } else if (editTodayBooking.getDriverId() != null && editTodayBooking.getDriverId().compareTo("") != 0
                    && !driverOn) {
                changeDriverId = "";
            }

            if ((getZeroTimeDate(editTodayBooking.getStartDate())
                    .compareTo(getZeroTimeDate(startDateToRestore)) == 0
                    && getZeroTimeDate(editTodayBooking.getEndDate())
                            .compareTo(getZeroTimeDate(endDateToRestore)) == 0)
                    && ((editTodayBooking.getDriverId() != null && editTodayBooking.getDriverId().compareTo("") != 0
                            && driverOn)
                            || ((editTodayBooking.getDriverId() == null
                                    || editTodayBooking.getDriverId().compareTo("") == 0) && !driverOn))) {
                if (Math.abs(oldDamageCharge - editTodayBooking.getDamageCharge()) > 0.01) {
                    newEditPrice = editTodayBooking.getTotalPrice() - oldDamageCharge
                            + editTodayBooking.getDamageCharge();
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;
                    confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                            + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                            + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                            + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                } else {
                    newEditPrice = editTodayBooking.getTotalPrice();
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;
                    confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                }
            } else {
                CarDto currentCar = carService.getCarById(editTodayBooking.getCarId());

                if (returnCarMode && getZeroTimeDate(editTodayBooking.getEndDate())
                        .compareTo(getZeroTimeDate(endDateToRestore)) < 0) {
                    if (Math.abs(oldDamageCharge - editTodayBooking.getDamageCharge()) > 0.01) {
                        newEditPrice = editTodayBooking.getTotalPrice() - oldDamageCharge
                                + editTodayBooking.getDamageCharge();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                                + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                                + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                                + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                    } else {
                        newEditPrice = editTodayBooking.getTotalPrice();

                        // Rounding
                        newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                        confirmMessage = dictionaryController.getDictionary().get("Confirm edit booking");
                    }
                } else {
                    if (!driverOn) {
                        newEditPrice = currentCar.getPriceNoDriver()
                                * (int) ((editTodayBooking.getEndDate().getTime()
                                        - editTodayBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                    } else {
                        newEditPrice = currentCar.getPriceWithDriver()
                                * (int) ((editTodayBooking.getEndDate().getTime()
                                        - editTodayBooking.getStartDate().getTime()) / (1000 * 60 * 60 * 24));
                    }

                    if (overdueCharge && getZeroTimeDate(editTodayBooking.getEndDate())
                            .compareTo(getZeroTimeDate(endDateToRestore)) > 0) {
                        newEditPrice += currentCar.getPriceOverdue()
                                * (int) ((editTodayBooking.getEndDate().getTime() - endDateToRestore.getTime())
                                        / (1000 * 60 * 60 * 24));
                    }

                    // Add damage charge
                    newEditPrice += editTodayBooking.getDamageCharge();

                    if (currentCar.getCurrency().compareTo(editTodayBooking.getCurrency()) != 0) {
                        if (currencyMap.containsKey(currentCar.getCurrency() + editTodayBooking.getCurrency())) {
                            newEditPrice = newEditPrice
                                    * currencyMap.get(currentCar.getCurrency() + editTodayBooking.getCurrency());
                        } else {
                            newEditPrice = newEditPrice * currencyMap.get(currentCar.getCurrency() + "USD")
                                    * currencyMap.get("USD" + editTodayBooking.getCurrency());
                        }
                    }
                    // Rounding
                    newEditPrice = (double) Math.round(newEditPrice * 100) / 100;

                    confirmMessage = dictionaryController.getDictionary().get("Old price") + ": "
                            + editTodayBooking.getTotalPrice() + " (" + editTodayBooking.getCurrency() + ")"
                            + "<br/>" + "<br/>" + dictionaryController.getDictionary().get("New price") + ": "
                            + newEditPrice + " (" + editTodayBooking.getCurrency() + ")";
                }
            }

            // Show confirm dialog
            RequestContext.getCurrentInstance().execute("todayApplyConfirmDialog_w.show()");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void reassign() throws IOException {
        try {
            if (reassignMode) {
                if (selectedParameters.length == 1) {
                    if (selectedParameters[0] == 1) {
                        reassignBooking.setCarId(reassignCarId);
                        if (applyNewPrice) {
                            reassignBooking.setTotalPrice(reassignCar.getTotalPrice());
                        }
                        if (reassignBooking.getStatus().compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0
                                || reassignBooking.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0) {
                            reassignBooking.setStatus("NEED DRIVER REPLACEMENT");
                            reassignBooking.setStatusToDisplay(
                                    dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                        } else {
                            reassignBooking.setStatus("BOOKED");
                            reassignBooking.setStatusToDisplay(dictionaryController.getDictionary().get("BOOKED"));
                        }
                    } else {
                        reassignBooking.setDriverId(reassignDriverId);
                        if (reassignBooking.getStatus().compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0
                                || reassignBooking.getStatus().compareTo("NEED CAR REPLACEMENT") == 0) {
                            reassignBooking.setStatus("NEED CAR REPLACEMENT");
                            reassignBooking.setStatusToDisplay(
                                    dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                        } else {
                            reassignBooking.setStatus("BOOKED");
                            reassignBooking.setStatusToDisplay(dictionaryController.getDictionary().get("BOOKED"));
                        }
                    }
                } else {
                    reassignBooking.setCarId(reassignCarId);
                    reassignBooking.setDriverId(reassignDriverId);
                    if (applyNewPrice) {
                        reassignBooking.setTotalPrice(reassignCar.getTotalPrice());
                    }
                    reassignBooking.setStatus("BOOKED");
                    reassignBooking.setStatusToDisplay(dictionaryController.getDictionary().get("BOOKED"));
                }

                if (editMode) {
                    bookingService.editBooking(reassignBooking);

                    if (editBooking.isOverdue()) {
                        editBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
                    } else {
                        editBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
                    }

                    // Update today booking table
                    int index = findTodayBookingData(reassignBooking.getId());
                    if (index >= 0) {
                        if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                                || getZeroTimeDate(editBooking.getEndDate())
                                        .compareTo(getZeroTimeDate(new Date())) == 0) {
                            baseTodayFullBookingList.add(index, reassignBooking);
                            baseTodayFullBookingList.remove(index + 1);
                        } else {
                            baseTodayFullBookingList.remove(index);
                        }

                    } else {
                        if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                                || getZeroTimeDate(editBooking.getEndDate())
                                        .compareTo(getZeroTimeDate(new Date())) == 0) {
                            baseTodayFullBookingList.add(editBooking);
                        }
                    }

                    editBooking = null;
                    editMode = false;
                    overdueCharge = false;
                } else if (todayEditMode) {
                    bookingService.editBooking(reassignBooking);

                    if (editTodayBooking.isOverdue()) {
                        editTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
                    } else {
                        editTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
                    }

                    // Update the other table
                    int index = findBookingData(editTodayBooking.getId());
                    if (index >= 0) {
                        baseFullBookingList.add(index, editTodayBooking);
                        baseFullBookingList.remove(index + 1);
                    }

                    // Remove booking from table if it is not today
                    if (getZeroTimeDate(editTodayBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) != 0
                            && getZeroTimeDate(editTodayBooking.getEndDate())
                                    .compareTo(getZeroTimeDate(new Date())) != 0) {
                        index = findTodayBookingData(editTodayBooking.getId());
                        if (index >= 0) {
                            baseTodayFullBookingList.remove(index);
                        }
                    }

                    editTodayBooking = null;
                    todayEditMode = false;
                    overdueCharge = false;
                }
            }

            if (conflictBookingList.size() > 0
                    && reassignBooking.getId() == conflictBookingList.get(0).getFirst()) {
                conflictBookingList.remove(0);
            }

            reassignBooking = null;
            selectedParameters = new int[0];
            reassignMode = false;
            if (conflictBookingList.size() > 0 && resolveConflictMode) {
                startResolveConflict();
            } else {
                resolveConflictMode = false;
            }

            reassignCarId = -1;
            reassignDriverId = "";
            reassignPage = 0;

            baseCarList.clear();
            reassignCar = null;
            afterCheck = false;
            carReassign = false;
        } catch (IOException e) {
            logger.error("Booking data update error.", e);
            sessionManager.addGlobalMessageFatal("Booking data update error.", null);
            throw e;
        }
    }

    public void reassignNext() {
        reassignMode = false;
        selectedParameters = new int[0];

        reassignCarId = -1;
        reassignDriverId = "";
        reassignPage = 0;

        baseCarList.clear();
        reassignCar = null;
        afterCheck = false;
        carReassign = false;

        if (conflictBookingList.size() > 0 && reassignBooking.getId() == conflictBookingList.get(0).getFirst()) {
            conflictBookingList.remove(0);
        }

        reassignBooking = null;

        if (conflictBookingList.size() > 0 && resolveConflictMode) {
            startResolveConflict();
        } else {
            resolveConflictMode = false;
        }
    }

    public void reassignCannotResolve() {
        if (reassignBooking == null) {
            FacesContext.getCurrentInstance().addMessage("messageReassignDialog",
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                            dictionaryController.getDictionary().get("PLEASE_SELECT_A_BOOKING"), null));
            return;
        }

        reassignBooking.setStatus("UNRESOLVABLE");
        reassignBooking.setStatusToDisplay(dictionaryController.getDictionary().get("UNRESOLVABLE"));

        try {
            bookingService.editBooking(reassignBooking);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (editMode) {
            if (editBooking.isOverdue()) {
                editBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
            } else {
                editBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
            }

            // Update today booking table
            int index = findTodayBookingData(reassignBooking.getId());
            if (index >= 0) {
                if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                        || getZeroTimeDate(editBooking.getEndDate()).compareTo(getZeroTimeDate(new Date())) == 0) {
                    baseTodayFullBookingList.add(index, reassignBooking);
                    baseTodayFullBookingList.remove(index + 1);
                } else {
                    baseTodayFullBookingList.remove(index);
                }

            } else {
                if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                        || getZeroTimeDate(editBooking.getEndDate()).compareTo(getZeroTimeDate(new Date())) == 0) {
                    baseTodayFullBookingList.add(editBooking);
                }
            }

            editBooking = null;
            editMode = false;
            overdueCharge = false;
        } else if (todayEditMode) {
            if (editTodayBooking.isOverdue()) {
                editTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
            } else {
                editTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
            }

            // Update the other table
            int index = findBookingData(editTodayBooking.getId());
            if (index >= 0) {
                baseFullBookingList.add(index, editTodayBooking);
                baseFullBookingList.remove(index + 1);
            }

            // Remove booking from table if it is not today
            if (getZeroTimeDate(editTodayBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) != 0
                    && getZeroTimeDate(editTodayBooking.getEndDate()).compareTo(getZeroTimeDate(new Date())) != 0) {
                index = findTodayBookingData(editTodayBooking.getId());
                if (index >= 0) {
                    baseTodayFullBookingList.remove(index);
                }
            }

            editTodayBooking = null;
            todayEditMode = false;
            overdueCharge = false;
        }

        if (conflictBookingList.size() > 0 && reassignBooking.getId() == conflictBookingList.get(0).getFirst()) {
            conflictBookingList.remove(0);
        }

        reassignBooking = null;
        selectedParameters = new int[0];
        reassignMode = false;

        if (conflictBookingList.size() > 0 && resolveConflictMode) {
            startResolveConflict();
        } else {
            resolveConflictMode = false;
        }

        reassignCarId = -1;
        reassignDriverId = "";
        reassignPage = 0;

        baseCarList.clear();
        reassignCar = null;
        afterCheck = false;
        carReassign = false;
    }

    public void startDeliverCar() {
        deliverCarMode = true;
    }

    public void startTodayDeliverCar() {
        deliverCarMode = true;
    }

    public void deliverCarApply() {
        try {
            selectedBooking.setStatus("SERVING");
            selectedBooking.setStatusToDisplay(dictionaryController.getDictionary().get("SERVING"));

            bookingService.editBooking(selectedBooking);

            if (selectedBooking.isOverdue()) {
                selectedBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
            } else {
                selectedBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
            }

            // Update today booking table
            int index = findTodayBookingData(selectedBooking.getId());
            if (index >= 0) {
                if (getZeroTimeDate(selectedBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                        || getZeroTimeDate(selectedBooking.getEndDate())
                                .compareTo(getZeroTimeDate(new Date())) == 0) {
                    baseTodayFullBookingList.add(index, selectedBooking);
                    baseTodayFullBookingList.remove(index + 1);
                }
            }
        } catch (IOException e) {
            logger.error("Booking data update error.", e);
            sessionManager.addGlobalMessageFatal("Booking data update error.", null);
        }

        deliverCarMode = false;
    }

    public void todayDeliverCarApply() {
        try {
            selectedTodayBooking.setStatus("SERVING");
            selectedTodayBooking.setStatusToDisplay(dictionaryController.getDictionary().get("SERVING"));

            bookingService.editBooking(selectedTodayBooking);

            if (selectedTodayBooking.isOverdue()) {
                selectedTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
            } else {
                selectedTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
            }

            // Update booking table
            int index = findBookingData(selectedTodayBooking.getId());
            if (index >= 0) {
                baseFullBookingList.add(index, selectedTodayBooking);
                baseFullBookingList.remove(index + 1);
            }
        } catch (IOException e) {
            logger.error("Booking data update error.", e);
            sessionManager.addGlobalMessageFatal("Booking data update error.", null);
        }

        deliverCarMode = false;
    }

    public void deliverCarDiscard() {
        deliverCarMode = false;
    }

    public void todayDeliverCarDiscard() {
        deliverCarMode = false;
    }

    public void apply() throws IOException {
        try {
            if (editMode) {
                editBooking.setBookingAdjustmentCharge(newBookingAdjustmentCharge);
                editBooking.setTotalPrice(newEditPrice);

                if ((editBooking.getDriverId() == null || editBooking.getDriverId().compareTo("") == 0)
                        && driverOn) {
                    editBooking.setDriverId(changeDriverId);
                } else if (editBooking.getDriverId() != null && editBooking.getDriverId().compareTo("") != 0
                        && !driverOn) {
                    editBooking.setDriverId("");
                }

                if (editBooking.getStatus().compareTo("SERVING") == 0 && returnCarMode) {
                    editBooking.setStatus("COMPLETED");
                }

                bookingService.editBooking(editBooking);

                if (editBooking.getStatus().compareTo("BOOKED") == 0) {
                    editBooking.setStatusToDisplay(dictionaryController.getDictionary().get("BOOKED"));
                } else if (editBooking.getStatus().compareTo("SERVING") == 0) {
                    editBooking.setStatusToDisplay(dictionaryController.getDictionary().get("SERVING"));
                } else if (editBooking.getStatus().compareTo("COMPLETED") == 0) {
                    editBooking.setStatusToDisplay(dictionaryController.getDictionary().get("COMPLETED"));
                } else if (editBooking.getStatus().compareTo("NEED CAR REPLACEMENT") == 0) {
                    editBooking
                            .setStatusToDisplay(dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                } else if (editBooking.getStatus().compareTo("UNRESOLVABLE") == 0) {
                    editBooking.setStatusToDisplay(dictionaryController.getDictionary().get("UNRESOLVABLE"));
                } else if (editBooking.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0) {
                    editBooking.setStatusToDisplay(
                            dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                } else if (editBooking.getStatus().compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                    editBooking.setStatusToDisplay(
                            dictionaryController.getDictionary().get("NEED CAR AND DRIVER REPLACEMENT"));
                }

                if (editBooking.isOverdue()) {
                    editBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
                } else {
                    editBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
                }

                // Update today booking table
                int index = findTodayBookingData(editBooking.getId());
                if (index >= 0) {
                    if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                            || getZeroTimeDate(editBooking.getEndDate())
                                    .compareTo(getZeroTimeDate(new Date())) == 0) {
                        baseTodayFullBookingList.add(index, editBooking);
                        baseTodayFullBookingList.remove(index + 1);
                    } else {
                        baseTodayFullBookingList.remove(index);
                    }

                } else {
                    if (getZeroTimeDate(editBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) == 0
                            || getZeroTimeDate(editBooking.getEndDate())
                                    .compareTo(getZeroTimeDate(new Date())) == 0) {
                        baseTodayFullBookingList.add(editBooking);
                    }
                }

                if (sendCarForMaintenance) {
                    carService.markCarAsMaintenance(editBooking.getCarId());

                    MaintenanceDto maintenanceDto = new MaintenanceDto(-1, editBooking.getCarId(), "CUSTOMER FAULT",
                            getZeroTimeDate(new Date()), null, "", 0);
                    maintenanceService.addMaintenance(maintenanceDto);

                    List<Integer> affectedBookingList = bookingService
                            .getBookingListForBrokenCar(editBooking.getCarId());

                    int idx;
                    FullBookingDto affectedBookingDto;
                    for (int i = 0; i < affectedBookingList.size(); i++) {
                        bookingService.markBookingAsNeedCarReplacement(affectedBookingList.get(i).intValue());

                        // Update 2 tables
                        idx = findTodayBookingData(affectedBookingList.get(i).intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseTodayFullBookingList.get(idx);
                            if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                    || affectedBookingDto.getStatus()
                                            .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            } else {
                                affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(
                                        dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                            }
                        }

                        idx = findBookingData(affectedBookingList.get(i).intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseFullBookingList.get(idx);
                            if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                    || affectedBookingDto.getStatus()
                                            .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            } else {
                                affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(
                                        dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                            }
                        }
                    }
                }

                // Case when customer already have car and call Staff to inform he will return car late
                if (!returnCarMode && editBooking.getStatus().compareTo("SERVING") == 0) {
                    List<Pair<Integer, Integer>> affectedBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                            .getConflictBookingList(editBooking);

                    int idx;
                    FullBookingDto affectedBookingDto;
                    for (int i = 0; i < affectedBookingList.size(); i++) {
                        if (affectedBookingList.get(i).getSecond().intValue() == 1) {
                            bookingService.markBookingAsNeedCarReplacement(
                                    affectedBookingList.get(i).getFirst().intValue());
                        } else if (affectedBookingList.get(i).getSecond().intValue() == 2) {
                            bookingService.markBookingAsNeedDriverReplacement(
                                    affectedBookingList.get(i).getFirst().intValue());
                        } else if (affectedBookingList.get(i).getSecond().intValue() == 3) {
                            bookingService.markBookingAsNeedCarAndDriverReplacement(
                                    affectedBookingList.get(i).getFirst().intValue());
                        }

                        // Update 2 tables
                        idx = findTodayBookingData(affectedBookingList.get(i).getFirst().intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseTodayFullBookingList.get(idx);

                            if (affectedBookingList.get(i).getSecond().intValue() == 1) {
                                if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 2) {
                                if (affectedBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 3) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            }
                        }

                        idx = findBookingData(affectedBookingList.get(i).getFirst().intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseFullBookingList.get(idx);

                            if (affectedBookingList.get(i).getSecond().intValue() == 1) {
                                if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 2) {
                                if (affectedBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 3) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            }
                        }
                    }
                }
            }
            editBooking = null;
            editMode = false;
            overdueCharge = false;

            returnCarMode = false;
        } catch (IOException e) {
            logger.error("Booking data update error.", e);
            sessionManager.addGlobalMessageFatal("Booking data update error.", null);
            throw e;
        }
    }

    public void todayApply() throws IOException {
        try {
            if (todayEditMode) {
                editTodayBooking.setBookingAdjustmentCharge(newBookingAdjustmentCharge);
                editTodayBooking.setTotalPrice(newEditPrice);

                if ((editTodayBooking.getDriverId() == null || editTodayBooking.getDriverId().compareTo("") == 0)
                        && driverOn) {
                    editTodayBooking.setDriverId(changeDriverId);
                } else if (editTodayBooking.getDriverId() != null
                        && editTodayBooking.getDriverId().compareTo("") != 0 && !driverOn) {
                    editTodayBooking.setDriverId("");
                }

                if (editTodayBooking.getStatus().compareTo("SERVING") == 0 && returnCarMode) {
                    editTodayBooking.setStatus("COMPLETED");
                }

                bookingService.editBooking(editTodayBooking);

                if (editTodayBooking.getStatus().compareTo("BOOKED") == 0) {
                    editTodayBooking.setStatusToDisplay(dictionaryController.getDictionary().get("BOOKED"));
                } else if (editTodayBooking.getStatus().compareTo("SERVING") == 0) {
                    editTodayBooking.setStatusToDisplay(dictionaryController.getDictionary().get("SERVING"));
                } else if (editTodayBooking.getStatus().compareTo("COMPLETED") == 0) {
                    editTodayBooking.setStatusToDisplay(dictionaryController.getDictionary().get("COMPLETED"));
                } else if (editTodayBooking.getStatus().compareTo("NEED CAR REPLACEMENT") == 0) {
                    editTodayBooking
                            .setStatusToDisplay(dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                } else if (editTodayBooking.getStatus().compareTo("UNRESOLVABLE") == 0) {
                    editTodayBooking.setStatusToDisplay(dictionaryController.getDictionary().get("UNRESOLVABLE"));
                } else if (editTodayBooking.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0) {
                    editTodayBooking.setStatusToDisplay(
                            dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                } else if (editTodayBooking.getStatus().compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                    editTodayBooking.setStatusToDisplay(
                            dictionaryController.getDictionary().get("NEED CAR AND DRIVER REPLACEMENT"));
                }

                if (editTodayBooking.isOverdue()) {
                    editTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("Yes"));
                } else {
                    editTodayBooking.setOverdueToDisplay(dictionaryController.getDictionary().get("No"));
                }

                // Update the other table
                int index = findBookingData(editTodayBooking.getId());
                if (index >= 0) {
                    baseFullBookingList.add(index, editTodayBooking);
                    baseFullBookingList.remove(index + 1);
                }

                // Remove booking from table if it is not today
                if (getZeroTimeDate(editTodayBooking.getStartDate()).compareTo(getZeroTimeDate(new Date())) != 0
                        && getZeroTimeDate(editTodayBooking.getEndDate())
                                .compareTo(getZeroTimeDate(new Date())) != 0) {
                    index = findTodayBookingData(editTodayBooking.getId());
                    if (index >= 0) {
                        baseTodayFullBookingList.remove(index);
                    }
                }

                if (sendCarForMaintenance) {
                    carService.markCarAsMaintenance(editTodayBooking.getCarId());

                    MaintenanceDto maintenanceDto = new MaintenanceDto(-1, editTodayBooking.getCarId(),
                            "CUSTOMER FAULT", getZeroTimeDate(new Date()), null, "", 0);
                    maintenanceService.addMaintenance(maintenanceDto);

                    List<Integer> affectedBookingList = bookingService
                            .getBookingListForBrokenCar(editTodayBooking.getCarId());

                    int idx;
                    FullBookingDto affectedBookingDto;
                    for (int i = 0; i < affectedBookingList.size(); i++) {
                        bookingService.markBookingAsNeedCarReplacement(affectedBookingList.get(i).intValue());

                        // Update 2 tables
                        idx = findTodayBookingData(affectedBookingList.get(i).intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseTodayFullBookingList.get(idx);
                            if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                    || affectedBookingDto.getStatus()
                                            .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            } else {
                                affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(
                                        dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                            }
                        }

                        idx = findBookingData(affectedBookingList.get(i).intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseFullBookingList.get(idx);
                            if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                    || affectedBookingDto.getStatus()
                                            .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            } else {
                                affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(
                                        dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                            }
                        }
                    }
                }

                // Case when customer already have car and call Staff to inform he will return car late
                if (!returnCarMode && editTodayBooking.getStatus().compareTo("SERVING") == 0) {
                    List<Pair<Integer, Integer>> affectedBookingList = (Vector<Pair<Integer, Integer>>) bookingService
                            .getConflictBookingList(editTodayBooking);

                    int idx;
                    FullBookingDto affectedBookingDto;
                    for (int i = 0; i < affectedBookingList.size(); i++) {
                        if (affectedBookingList.get(i).getSecond().intValue() == 1) {
                            bookingService.markBookingAsNeedCarReplacement(
                                    affectedBookingList.get(i).getFirst().intValue());
                        } else if (affectedBookingList.get(i).getSecond().intValue() == 2) {
                            bookingService.markBookingAsNeedDriverReplacement(
                                    affectedBookingList.get(i).getFirst().intValue());
                        } else if (affectedBookingList.get(i).getSecond().intValue() == 3) {
                            bookingService.markBookingAsNeedCarAndDriverReplacement(
                                    affectedBookingList.get(i).getFirst().intValue());
                        }

                        // Update 2 tables
                        idx = findTodayBookingData(affectedBookingList.get(i).getFirst().intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseTodayFullBookingList.get(idx);

                            if (affectedBookingList.get(i).getSecond().intValue() == 1) {
                                if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 2) {
                                if (affectedBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 3) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            }
                        }

                        idx = findBookingData(affectedBookingList.get(i).getFirst().intValue());
                        if (idx >= 0) {
                            affectedBookingDto = baseFullBookingList.get(idx);

                            if (affectedBookingList.get(i).getSecond().intValue() == 1) {
                                if (affectedBookingDto.getStatus().compareTo("NEED DRIVER REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED CAR REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED CAR REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 2) {
                                if (affectedBookingDto.getStatus().compareTo("NEED CAR REPLACEMENT") == 0
                                        || affectedBookingDto.getStatus()
                                                .compareTo("NEED CAR AND DRIVER REPLACEMENT") == 0) {
                                    affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                            .get("NEED CAR AND DRIVER REPLACEMENT"));
                                } else {
                                    affectedBookingDto.setStatus("NEED DRIVER REPLACEMENT");
                                    affectedBookingDto.setStatusToDisplay(
                                            dictionaryController.getDictionary().get("NEED DRIVER REPLACEMENT"));
                                }
                            } else if (affectedBookingList.get(i).getSecond().intValue() == 3) {
                                affectedBookingDto.setStatus("NEED CAR AND DRIVER REPLACEMENT");
                                affectedBookingDto.setStatusToDisplay(dictionaryController.getDictionary()
                                        .get("NEED CAR AND DRIVER REPLACEMENT"));
                            }
                        }
                    }
                }
            }
            editTodayBooking = null;
            todayEditMode = false;
            overdueCharge = false;

            returnCarMode = false;
        } catch (IOException e) {
            logger.error("Booking data update error.", e);
            sessionManager.addGlobalMessageFatal("Booking data update error.", null);
            throw e;
        }
    }

    public void emailRemind() {
        Email email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
        email.setSSLOnConnect(true);
        try {
            email.setFrom("easycarremind@gmail.com");
            email.setSubject("Reminder to return car");
            email.setMsg("Dear " + selectedBooking.getCustomerName()
                    + ",\n\nPlease note that you are supposed to return the car with id "
                    + selectedBooking.getCarId() + " to us on " + selectedBooking.getEndDateToDisplay()
                    + "\n\nBest regards,\nEasy Car Team.");
            email.addTo(selectedBooking.getCustomerEmail());
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }

        selectedBooking.setLastEmailRemindDate(getZeroTimeDate(new Date()));
        try {
            bookingService.editBooking(selectedBooking);
        } catch (IOException e) {
            e.printStackTrace();
        }

        FacesContext.getCurrentInstance().addMessage("messageDetailDialog", new FacesMessage(
                FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
    }

    public void phoneRemind() {
        selectedBooking.setLastPhoneRemindDate(getZeroTimeDate(new Date()));
        try {
            bookingService.editBooking(selectedBooking);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void emailRemindAll() {
        FullBookingDto currentFullBookingDto;
        for (int i = 0; i < baseFullBookingList.size(); i++) {
            currentFullBookingDto = baseFullBookingList.get(i);

            if (!currentFullBookingDto.isRemindButtonOn()) {
                continue;
            }

            Email email = new SimpleEmail();
            email.setHostName("smtp.googlemail.com");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("easycarremind", "easycartest"));
            email.setSSLOnConnect(true);

            try {
                email.setFrom("easycarremind@gmail.com");
                email.setSubject("Reminder to return car");
                email.setMsg("Dear " + currentFullBookingDto.getCustomerName()
                        + ",\n\nPlease note that you are supposed to return the car with id "
                        + currentFullBookingDto.getCarId() + " to us on "
                        + currentFullBookingDto.getEndDateToDisplay() + "\n\nBest regards,\nEasy Car Team.");
                email.addTo(currentFullBookingDto.getCustomerEmail());
                email.send();
            } catch (EmailException e) {
                e.printStackTrace();
            }

            currentFullBookingDto.setLastEmailRemindDate(getZeroTimeDate(new Date()));
            try {
                bookingService.editBooking(currentFullBookingDto);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        FacesContext.getCurrentInstance().addMessage("messageEmailRemindAll", new FacesMessage(
                FacesMessage.SEVERITY_INFO, dictionaryController.getDictionary().get("REMINDER_SENT"), null));
    }

    public static Date getZeroTimeDate(Date fecha) {
        Date res = fecha;
        Calendar calendar = Calendar.getInstance();

        calendar.setTime(fecha);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        res = calendar.getTime();

        return res;
    }

    public void discard() throws IOException {
        editBooking = null;
        editMode = false;
        overdueCharge = false;

        selectedBooking.setStartDate(startDateToRestore);
        selectedBooking.setEndDate(endDateToRestore);
        selectedBooking.setStatus(statusToRestore);
        selectedBooking.setRemindRemark(remindRemarkToRestore);
        selectedBooking.setReturnRemark(returnRemarkToRestore);
        selectedBooking.setDamageCharge(oldDamageCharge);

        reassignMode = false;
        reassignBooking = null;
        selectedParameters = new int[0];

        conflictBookingList.clear();
        reassignCarId = -1;
        reassignDriverId = "";
        reassignPage = 0;

        baseCarList.clear();
        reassignCar = null;
        afterCheck = false;
        carReassign = false;

        returnCarMode = false;
    }

    public void todayDiscard() throws IOException {
        editTodayBooking = null;
        todayEditMode = false;
        overdueCharge = false;

        selectedTodayBooking.setStartDate(startDateToRestore);
        selectedTodayBooking.setEndDate(endDateToRestore);
        selectedTodayBooking.setStatus(statusToRestore);
        selectedTodayBooking.setRemindRemark(remindRemarkToRestore);
        selectedTodayBooking.setReturnRemark(returnRemarkToRestore);
        selectedTodayBooking.setDamageCharge(oldDamageCharge);

        reassignMode = false;
        reassignBooking = null;
        selectedParameters = new int[0];

        conflictBookingList.clear();
        reassignCarId = -1;
        reassignDriverId = "";
        reassignPage = 0;

        baseCarList.clear();
        reassignCar = null;
        afterCheck = false;
        carReassign = false;

        returnCarMode = false;
    }

    public void reassignDiscard() {
        reassignMode = false;
        reassignBooking = null;
        selectedParameters = new int[0];

        //conflictBookingList.clear();
        //reassignCarId = -1;
        //reassignDriverId = "";
        //reassignPage = 0;

        baseCarList.clear();
        reassignCar = null;
        afterCheck = false;
        carReassign = false;

        resolveConflictMode = false;

        if (editMode) {
            editBooking.setDriverId(oldDriverId);
            editBooking.setTotalPrice(oldTotalPrice);
        } else if (todayEditMode) {
            editTodayBooking.setDriverId(oldDriverId);
            editTodayBooking.setTotalPrice(oldTotalPrice);
        }

    }

    public void damageChargeValidate(FacesContext context, UIComponent component, Object value) {
        String regex1 = "^[0-9]*\\.?[0-9]+$";
        String regex2 = "^[0-9]*\\.?[0-9]+E[0-9]+$";
        String price = value.toString().trim();

        validateFail = false;

        if (price.compareTo("") == 0) {
            validateFail = true;
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    dictionaryController.getDictionary().get("PRICE_CANNOT_BE_EMPTY"), null));
        }

        if (!price.matches(regex1) && !price.matches(regex2)) {
            validateFail = true;
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    dictionaryController.getDictionary().get("INVALID_PRICE"), null));
        }

        if (price.length() > 15) {
            validateFail = true;
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    dictionaryController.getDictionary().get("PRICE_CANNOT_HAVE_MORE_THAN_10_DIGITS"), null));
        }
    }

    public void remarkValidate(FacesContext context, UIComponent component, Object value) {
        String deliveryRemark = value.toString().trim();

        if (deliveryRemark.length() > 1000) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    dictionaryController.getDictionary().get("REMARK_CANNOT_HAVE_MORE_THAN_1000_CHARACTERS"),
                    null));
        }
    }

    /* This code required in order to start a conversation scope
     See boolList.xhtml */
    public void conversationBegin() {
        if (conversation.isTransient()) {
            conversation.begin();
        }
    }

    public void conversationEnd() {
        if (!conversation.isTransient()) {
            conversation.end();
        }
    }

    public String getConversationState() {
        return conversation.isTransient() ? "transient" : "long running";
    }

    public String logoff() {
        conversationEnd();
        sessionManager.logoff();
        return "/pages/myProfile.jsf?faces-redirect=true";
    }
}