/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.taxiservicios.beans.admin;


import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.GeneralPublicController;
import com.arrebol.taxiservicios.controller.admin.GenericValidationController;
import com.arrebol.taxiservicios.controller.admin.TaxiController;
import com.arrebol.taxiservicios.model.admin.GeneralPublic;
import com.arrebol.taxiservicios.model.admin.SaleDetailGeneralPublic;
import com.arrebol.taxiservicios.model.admin.SaleGeneralPublic;
import com.arrebol.taxiservicios.model.catalog.Color;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.catalog.Vehicle;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.TypeSale;
import java.io.Serializable;
import java.util.ArrayList;
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;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Named("generalPublicBean")
@ViewScoped
public class GeneralPublicBean extends TaxiGenericBean implements Serializable {

    /**
     *
     * @param outcome
     * @return
     */
    public String editCustomer(String outcome) {
        return outcome;
    }
    
    public List<SaleGeneralPublic> getDetails(String id) {
        logger.info("getDetails");
        try {
            setSaleGeneral(getController().findSaleForGeneralPublic(id));

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

    public void addPublicGeneral() {
 
            if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja general del día");
                return;
            }
            getAddGeneral().setActiveStatus(BasicType.ENEBLED);
            getAddGeneral().setCreatedBy(getLoggedUser());
            getAddGeneral().setCreatedOn(new Date());
            getAddGeneral().setId(UUID.randomUUID().toString());
            getAddGeneral().setVehicle(new Vehicle(idVehicle));
            getAddGeneral().setColor(new Color(idColor));
            getAddGeneral().setLocation(new Location(getLoggedUser().getLocation().getId()));
            getAddGeneral().setAdeudo(0D);
            getAddGeneral().setKmMaintenance(0F);

            boolean success = getController().addGeneralPublic(getAddGeneral());
            
            if (success) {
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Público general",
                        "Se agregó el cliente correctamente");
                
                if(getGeneral() != null)
                    getGeneral().clear();
            
                setGeneral(getController().fillGeneralPublic());
            }    

    }
    
    public void addSaleDetailPublicGeneral() {
        if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            if(getGenericController().existStableSmallBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja chica del día");
                return;
            }
            if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja general del día");
                return;
            }
        
        getAddSaleDetail().setActiveStatus(BasicType.ENEBLED);
        getAddSaleDetail().setCreatedBy(getLoggedUser());
        getAddSaleDetail().setCreatedOn(new Date());
        getAddSaleDetail().setId(UUID.randomUUID().toString());
        getAddSaleDetail().setSaleGeneralPublic(new SaleGeneralPublic(selectedSaleGeneral.getId()));
        
        boolean success = getController().addSaleDetailGeneralPublic(getAddSaleDetail());
        if (success) {
            if(getSaleGeneral() != null)
                    getSaleGeneral().clear();
            
            setSaleGeneral(getController().findSaleCreditForGeneralPublic());
            
            SaleGeneralPublic tmp = getController().getByIdSaleGeneralPublic(selectedSaleGeneral.getId());
            double adeudo = (tmp.getAdeudo() - getAddSaleDetail().getAmount());
            tmp.setAdeudo(adeudo);
            
            getController().updateAdeudoByIdSaleGeneralPublic(tmp, tmp.getId());
            
            GeneralPublic tmp2 = getController().getById(tmp.getGeneralPublic().getId());
            double adeudo2 = (tmp2.getAdeudo() - getAddSaleDetail().getAmount());
            tmp2.setAdeudo(adeudo2);
            
            getController().updateAdeudoById(tmp2, tmp2.getId());
            
            showMessage(FacesMessage.SEVERITY_INFO,
                        "Abono público general",
                        "Se agregó el abono correctamente");
        }
    }
    
    public void addSalePublicGeneral() {
            if (getGenericController().existClosingDayByCreatedOn(new Date(), getLoggedUser())) {
                showMessage(FacesMessage.SEVERITY_WARN,
                        "Error",
                        "No se puede hacer ninguna acción si existe un corte del día");
                return;
            }
            if(getGenericController().existStableSmallBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja chica del día");
                return;
            }
            if(getGenericController().existStableGeneralBoxByCurdate(getLoggedUser()))
            {
                showMessage(FacesMessage.SEVERITY_WARN,
                            "Dia cerrado",
                            "No se puede hacer ninguna acción porque ya existe un cuadre de caja general del día");
                return;
            }
            getAddSale().setActiveStatus(BasicType.ENEBLED);
            getAddSale().setCreatedBy(getLoggedUser());
            getAddSale().setCreatedOn(new Date());
            getAddSale().setId(UUID.randomUUID().toString());
            getAddSale().setGeneralPublic(new GeneralPublic(idGeneral));
            if(typeSale.equals("CASH"))
            {
                getAddSale().setTypeSale(TypeSale.CASH);
                getAddSale().setAdeudo(0D);
            }
            else
            {
                getAddSale().setTypeSale(TypeSale.CREDIT);
                getAddSale().setAdeudo(getAddSale().getAmount());
                
                
            }

            boolean success = getController().addSaleGeneralPublic(getAddSale());
            
            if (success) {
                
                if(getGeneral() != null)
                    getGeneral().clear();
            
                setGeneral(getController().fillGeneralPublic());
                
                GeneralPublic tmp = getController().getById(idGeneral);
                
                if(typeSale.equals("CREDIT")){
                    double adeudo = (tmp.getAdeudo() + getAddSale().getAdeudo());
                    tmp.setAdeudo(adeudo);
                }
                tmp.setKm(getAddSale().getKm());
                tmp.setKmMaintenance(getAddSale().getKmMaintenance());
                getController().updateAdeudoById(tmp, idGeneral);
                
                showMessage(FacesMessage.SEVERITY_INFO,
                        "Venta público general",
                        "Se agregó la venta correctamente");
                
            }    

    }
    
    public String seeDetails(String outcome) {
        return outcome;
    }

    @PostConstruct
    public void init() {
        try {
            loadBundlePropertyFile();

            setController(new GeneralPublicController());
            setTaxiController(new TaxiController());
            setGenericController(new GenericValidationController());

            setColor(getTaxiController().fillColorsComboBox());
            setVehicle(getTaxiController().fillVehicleComboBox());
            setGeneral(controller.fillGeneralPublic());
            
            setSaleGeneral(controller.findSaleCreditForGeneralPublic());
            
            addGeneral = new GeneralPublic();
            addSale = new SaleGeneralPublic();
            addSaleDetail = new SaleDetailGeneralPublic();
            
            if(getSaleGeneral() != null && !getSaleGeneral().isEmpty())
            {
                for(SaleGeneralPublic person : getSaleGeneral())
                {
                  totalFinancing += person.getAdeudo();
                }
            }
            
        } catch (Exception e) {
            logger.error("Finantial customer init", e);
        }
    }

    private static final long serialVersionUID = -7284027390656669184L;

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

    private GeneralPublicController controller;
    private GenericValidationController genericController;
    private TaxiController taxiController;
    private float totalFinancing;

    private List<GeneralPublic> general;
    private List<SaleGeneralPublic> saleGeneral;
    private List<Vehicle> vehicle;
    private List<Color> color;
    private String idVehicle;
    private String idColor;
    private String idGeneral;
    private String typeSale;
    private GeneralPublic addGeneral;
    private GeneralPublic selectedGeneral;
    private SaleGeneralPublic selectedSaleGeneral;
    private SaleGeneralPublic addSale;
    private SaleDetailGeneralPublic addSaleDetail;

    public GenericValidationController getGenericController() {
        return genericController;
    }

    public void setGenericController(GenericValidationController genericController) {
        this.genericController = genericController;
    }

    public GeneralPublicController getController() {
        return controller;
    }

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

    public TaxiController getTaxiController() {
        return taxiController;
    }

    public void setTaxiController(TaxiController taxiController) {
        this.taxiController = taxiController;
    }

    public List<GeneralPublic> getGeneral() {
        return general;
    }

    public void setGeneral(List<GeneralPublic> general) {
        this.general = general;
    }

    public List<Vehicle> getVehicle() {
        return vehicle;
    }

    public void setVehicle(List<Vehicle> vehicle) {
        this.vehicle = vehicle;
    }

    public List<Color> getColor() {
        return color;
    }

    public void setColor(List<Color> color) {
        this.color = color;
    }

    public String getIdVehicle() {
        return idVehicle;
    }

    public void setIdVehicle(String idVehicle) {
        this.idVehicle = idVehicle;
    }

    public String getIdColor() {
        return idColor;
    }

    public void setIdColor(String idColor) {
        this.idColor = idColor;
    }

    public GeneralPublic getAddGeneral() {
        return addGeneral;
    }

    public void setAddGeneral(GeneralPublic addGeneral) {
        this.addGeneral = addGeneral;
    }

    public GeneralPublic getSelectedGeneral() {
        return selectedGeneral;
    }

    public void setSelectedGeneral(GeneralPublic selectedGeneral) {
        this.selectedGeneral = selectedGeneral;
    }

    public List<SaleGeneralPublic> getSaleGeneral() {
        return saleGeneral;
    }

    public void setSaleGeneral(List<SaleGeneralPublic> saleGeneral) {
        this.saleGeneral = saleGeneral;
    }

    public String getIdGeneral() {
        return idGeneral;
    }

    public void setIdGeneral(String idGeneral) {
        this.idGeneral = idGeneral;
    }

    public SaleGeneralPublic getAddSale() {
        return addSale;
    }

    public void setAddSale(SaleGeneralPublic addSale) {
        this.addSale = addSale;
    }

    public String getTypeSale() {
        return typeSale;
    }

    public void setTypeSale(String typeSale) {
        this.typeSale = typeSale;
    }

    public SaleGeneralPublic getSelectedSaleGeneral() {
        return selectedSaleGeneral;
    }

    public void setSelectedSaleGeneral(SaleGeneralPublic selectedSaleGeneral) {
        this.selectedSaleGeneral = selectedSaleGeneral;
    }

    public SaleDetailGeneralPublic getAddSaleDetail() {
        return addSaleDetail;
    }

    public void setAddSaleDetail(SaleDetailGeneralPublic addSaleDetail) {
        this.addSaleDetail = addSaleDetail;
    }

    public float getTotalFinancing() {
        return totalFinancing;
    }

    public void setTotalFinancing(float totalFinancing) {
        this.totalFinancing = totalFinancing;
    }


}
