/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.arrebol.taxiservicios.beans.admin.client;

import com.arrebol.taxiservicios.beans.Datatable;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.CustomerController;
import com.arrebol.taxiservicios.controller.admin.ExpenseController;
import com.arrebol.taxiservicios.controller.sp.report.ReportCustomerPayController;
import com.arrebol.taxiservicios.model.admin.Expense;
import com.arrebol.taxiservicios.model.admin.FinancingCustomer;
import com.arrebol.taxiservicios.model.admin.Taxi;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.ExpenseStatusType;
import com.arrebol.taxiservicios.model.enums.ExpenseType;
import com.arrebol.taxiservicios.model.enums.PersonType;
import com.arrebol.taxiservicios.wrapper.PersonWrapper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Picasso
 */
@Named("customerListBean")
@ViewScoped
public class CustomerListBean extends TaxiGenericBean implements Serializable, Datatable {

    /**
     *
     * @param outcome
     * @return
     */
    public String editCustomer(String outcome) {
        //return "/app/admin/client/update";
        return outcome;
    }
    
    public List<Taxi> getDetails(String id) {
        logger.info("getDetails");
        try {
            setTaxis(getController().getTaxiByIdCustomer(id, getLoggedUser().getLocation().getId()));

            logger.info("detailsInvoice loaded size " + taxis != null ? taxis.size() : 0);
        } catch (Exception e) {
            logger.error("getDetailsInvoice", e);
        }
        return null == taxis ? new ArrayList<>() : taxis;
    }

    private static final long serialVersionUID = -7284027390656669184L;

    final Logger logger = LogManager.getLogger(CustomerListBean.class);

    CustomerController controller;
    ReportCustomerPayController reportController;
    ExpenseController expenseController;
    
    private List<PersonWrapper> customers;
    private List<Taxi> taxis;
    private PersonWrapper selectedCustomer;
    private FinancingCustomer financing;
    private String taxiId;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();
            financing = new FinancingCustomer();
            setController(new CustomerController());
            setReportController(new ReportCustomerPayController());
            setExpenseController(new ExpenseController());
            setCustomers(wraperPerson(getController().getAllPersonsByPersonTye(PersonType.CUSTOMER)));

            logger.info("Customers loaded");
        } catch (Exception e) {
            logger.error("init", e);
        }
    }

    public ExpenseController getExpenseController() {
        return expenseController;
    }

    public void setExpenseController(ExpenseController expenseController) {
        this.expenseController = expenseController;
    }

    public ReportCustomerPayController getReportController() {
        return reportController;
    }

    public void setReportController(ReportCustomerPayController reportController) {
        this.reportController = reportController;
    }
    
    public List<Taxi> getTaxisCombo() {
        return getController().fillTaxisComboBox();
    }

    public String getTaxiId() {
        return taxiId;
    }

    public void setTaxiId(String taxiId) {
        this.taxiId = taxiId;
    }

    public FinancingCustomer getFinancing() {
        return financing;
    }

    public void setFinancing(FinancingCustomer financing) {
        this.financing = financing;
    }

    public List<Taxi> getTaxis() {
        return taxis;
    }

    public void setTaxis(List<Taxi> taxis) {
        this.taxis = taxis;
    }

    public CustomerController getController() {
        return controller;
    }

    public void setController(CustomerController controller) {
        this.controller = controller;
    }

    public List<PersonWrapper> getCustomers() {
        return customers;
    }

    public void setCustomers(List<PersonWrapper> customers) {
        this.customers = customers;
    }

    public PersonWrapper getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(PersonWrapper selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    @Override
    public void editRow(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowCancel(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowReorder(ReorderEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void addRow() {
        if(taxiId != null && !taxiId.isEmpty())
        {
            Taxi taxiTemp = getController().getTaxiById(taxiId);
            getFinancing().setActiveStatus(BasicType.ENEBLED);
            getFinancing().setActuallyDebit(taxiTemp.getAdeudo() - getFinancing().getPayment());
            getFinancing().setCreatedBy(getLoggedUser());
            getFinancing().setCreatedOn(new Date());
            getFinancing().setDiscount(0D);
            getFinancing().setLastDebit(taxiTemp.getAdeudo());
            getFinancing().setMonthDebit(taxiTemp.getAdeudo());
            getFinancing().setTaxi(taxiTemp);
            getFinancing().setIncrease(0D);
            getFinancing().setId(UUID.randomUUID().toString());
            getFinancing().setActive(Boolean.TRUE);
            
            if(getReportController().saveFinancingClient(getFinancing()))
            {
                Expense expense = new Expense();
                expense.setId(UUID.randomUUID().toString());
                expense.setAmountMenudeo(getFinancing().getPayment());
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.HOUR, -6);
                expense.setCreatedOn(calendar.getTime());
                expense.setDescription("Abono de financiamiento");
                expense.setFolio("");
                expense.setPayment(getFinancing().getPayment());
                expense.setPaymentDate(calendar.getTime());
                expense.setStatus(ExpenseStatusType.AUTHORIZED);
                expense.setType(ExpenseType.ABONO_FINANCIAMIENTO);
                expense.setLocationSend(new Location(getLoggedUser().getId()));
                expense.setPaid(BasicType.DISABLED);
                expense.setFinance(BasicType.DISABLED);
                expense.setDepositStatus(ExpenseStatusType.AUTHORIZED);
                
                boolean success = getExpenseController().addExpense(
                    expense,
                    getLoggedUser().getId(),
                    (null != taxiId && !"".equals(taxiId.trim())) ? taxiId : null);
                
                if (success) {
                    showMessage(FacesMessage.SEVERITY_INFO,
                        "Abono al adeudo",
                        "Se agregó correctamente");
                }
                
                taxiTemp.setAdeudo((float) getFinancing().getActuallyDebit());
                getReportController().updateTaxiById(taxiTemp);
            }
            
            financing = new FinancingCustomer();
        }
    }

    @Override
    public void deleteRow() {
        logger.info("deleteRow");
        try {
            if (null == getLoggedUser().getPerson()
                    || null == getLoggedUser().getPerson().getId()
                    || getLoggedUser().getPerson().getId().equals(getSelectedCustomer().getId())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        getBundlePropertyFile().getString("customer.delete.title"),
                        getBundlePropertyFile().getString(
                                null == getLoggedUser().getPerson()
                                || null == getLoggedUser().getPerson().getId()
                                ? "customer.delete.cannot.empty"
                                : "customer.delete.cannot.delete"
                        ));
            } else {
                boolean success = getController().deletePersonById(
                        getSelectedCustomer().getId(), getLoggedUser().getUserName());

                if (success) {
                    getCustomers().remove(getSelectedCustomer());
                    setSelectedCustomer(null);

                    showMessage(FacesMessage.SEVERITY_INFO,
                            getBundlePropertyFile().getString("customer.delete.title"),
                            getBundlePropertyFile().getString("customer.delete.success.desc"));
                } else {
                    logger.error("Customer " + getSelectedCustomer() + "was not deleted");
                    showMessage(FacesMessage.SEVERITY_ERROR,
                            getBundlePropertyFile().getString("customer.delete.title"),
                            getBundlePropertyFile().getString("customer.delete.fail.desc"));
                }
            }
        } catch (Exception e) {
            logger.error("deleteRow: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("customer.delete.title"),
                    getBundlePropertyFile().getString("customer.delete.exception.desc"));
        }
    }

}
