/*
 * 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.provider;

import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.ProviderController;
import com.arrebol.taxiservicios.controller.catalog.LocationController;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.core.Address;
import com.arrebol.taxiservicios.model.core.ContactNumber;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.enums.AddressType;
import com.arrebol.taxiservicios.model.enums.PersonType;
import com.arrebol.taxiservicios.model.enums.PhoneType;
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;

/**
 *
 * @author Picasso
 */
@Named("providerAddBean")
@ViewScoped
public class ProviderAddBean extends TaxiGenericBean implements Serializable {

    /**
     * Save/Update an provider in the system.
     */
    public void addProvider() {
        logger.info("addProvider");
        try {
            if (!isAddProviderBtnOnclick()) {
                getProvider().setId(UUID.randomUUID().toString());
                getProvider().setActive(true);
                getProvider().setRoot(false);
                getProvider().setCreatedOn(new Date());
                getProvider().setLocation(new Location(getLoggedUser().getLocation().getId()));
                getProvider().setAjustador(Boolean.FALSE);
            } else {
                getProvider().setLastUpdatedOn(new Date());
            }

            boolean success = getController().addPerson(getProvider(), getLoggedUser().getUserName(), !isAddProviderBtnOnclick());

            if (success) {
                setAddProviderBtnOnclick(true);
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("provider.add.title"),
                        getBundlePropertyFile().getString("provider.add.success.desc"));
            } else {
                logger.error("Provider " + getProvider() + " was not " + (isAddProviderBtnOnclick() ? "updated" : "saved"));
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("provider.add.title"),
                        getBundlePropertyFile().getString("provider.add.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("addProvider: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("provider.add.title"),
                    getBundlePropertyFile().getString("provider.add.exception.desc"));
        }
    }

    /**
     * Add RFC, Email, CURP, and Local/Mobile phones to provider.
     */
    public void addContactDetails() {
        logger.info("addContactDetails");
        try {
            if (!isAddContactBtnOnclick()) {
                getContactNumbers().stream().map((contactNumber) -> {
                    contactNumber.setId(UUID.randomUUID().toString());
                    return contactNumber;
                }).forEachOrdered((contactNumber) -> {
                    contactNumber.setPerson(getProvider());
                    contactNumber.setCreatedOn(new Date());
                });
            } else {
                getContactNumbers().forEach((phone) -> {
                    phone.setLastUpdatedOn(new Date());
                });
            }
            getProvider().setLastUpdatedOn(new Date());

            boolean success = getController().saveOrUpdatePersonContactDetailsById(
                    getProvider().getId(), getProvider().getCurp(),
                    getProvider().getRfc(), getProvider().getMail(),
                    getContactNumbers(), getLoggedUser().getUserName(),
                    !isAddContactBtnOnclick(), !isAddContactBtnOnclick());
            if (success) {
                setAddContactBtnOnclick(true);
                logger.info("Contact detais saved.");
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("person.add.contact.title"),
                        getBundlePropertyFile().getString("person.add.contact.success.desc"));
            } else {
                logger.error("Contact details can not be saved.");
                logger.error("Contact details: " + getProvider());
                logger.error("Numbers details: " + getContactNumbers());
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("person.add.contact.title"),
                        getBundlePropertyFile().getString("person.add.contact.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("addContactDetails: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("person.add.contact.title"),
                    getBundlePropertyFile().getString("person.add.contact.exception.desc"));
        }
    }

    /**
     * Save an address(HOME) provider details.
     *
     * @param formName
     */
    public void addAddress(String formName) {
        logger.info("addAddress");
        try {
            /*
            getAddress().setStreet(facesContext().getExternalContext().getRequestParameterMap().get(formName + ":streetHdn"));
            getAddress().setExtendedAddress(facesContext().getExternalContext().getRequestParameterMap().get(formName + ":colonyHdn"));
            getAddress().setLocality(facesContext().getExternalContext().getRequestParameterMap().get(formName + ":departmentHdn"));
            getAddress().setRegion(facesContext().getExternalContext().getRequestParameterMap().get(formName + ":stateHdn"));
            getAddress().setZipCode(facesContext().getExternalContext().getRequestParameterMap().get(formName + ":cpHdn"));
            */
            if (!isAddAddressBtnOnclick()) {
                getAddress().setId(UUID.randomUUID().toString());
                getAddress().setCreatedOn(new Date());
            } else {
                getAddress().setLastUpdatedOn(new Date());
            }

            boolean success = getController().saveOrUpdateAddress(getAddress(), !isAddAddressBtnOnclick(), getProvider().getId(), getLoggedUser().getUserName());

            if (success) {
                setAddAddressBtnOnclick(true);
                logger.info("Address detais saved.");
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("person.add.address.title"),
                        getBundlePropertyFile().getString("person.add.address.success.desc"));
            } else {
                logger.error("Address details not saved " + getAddress());
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("person.add.address.title"),
                        getBundlePropertyFile().getString("person.add.address.fail.desc"));
            }

        } catch (Exception e) {
            logger.error("addAddress: " + e);

            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("person.add.address.title"),
                    getBundlePropertyFile().getString("person.add.address.exception.desc"));
        }
    }

    private static final long serialVersionUID = -4594340936069728620L;

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

    private ProviderController controller;
    private Person provider;
    private List<ContactNumber> contactNumbers;
    private Address address;
    private LocationController locationController;
    private List<Location> locations;

    private boolean addProviderBtnOnclick;
    private boolean addContactBtnOnclick;
    private boolean addAddressBtnOnclick;
    private boolean addPaymentBtnOnclick;
    private Date sixteenYearsOld;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            Calendar calendar = Calendar.getInstance();

            calendar.add(Calendar.YEAR, -15);
            setSixteenYearsOld(calendar.getTime());

            loadBundlePropertyFile();

            setController(new ProviderController());
            setLocationController(new LocationController());
            setLocations(getLocationController().fillLocationDatatable());
            setProvider(new Person(PersonType.PROVIDER));
            setAddress(new Address(AddressType.HOME));

            getContactNumbers().add(new ContactNumber(PhoneType.HOME));
            getContactNumbers().add(new ContactNumber(PhoneType.MOBILE));

            setAddProviderBtnOnclick(false);
            setAddContactBtnOnclick(false);
            setAddAddressBtnOnclick(false);
            setAddPaymentBtnOnclick(false);

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

    public LocationController getLocationController() {
        return locationController;
    }

    public void setLocationController(LocationController locationController) {
        this.locationController = locationController;
    }

    public List<Location> getLocations() {
        return locations;
    }

    public void setLocations(List<Location> locations) {
        this.locations = locations;
    }

    public ProviderController getController() {
        return controller;
    }

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

    public Person getProvider() {
        return provider;
    }

    public void setProvider(Person provider) {
        this.provider = provider;
    }

    public List<ContactNumber> getContactNumbers() {
        if (null == contactNumbers) {
            contactNumbers = new ArrayList<ContactNumber>();
        }
        return contactNumbers;
    }

    public void setContactNumbers(List<ContactNumber> contactNumbers) {
        this.contactNumbers = contactNumbers;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public boolean isAddProviderBtnOnclick() {
        return addProviderBtnOnclick;
    }

    public void setAddProviderBtnOnclick(boolean addProviderBtnOnclick) {
        this.addProviderBtnOnclick = addProviderBtnOnclick;
    }

    public boolean isAddContactBtnOnclick() {
        return addContactBtnOnclick;
    }

    public void setAddContactBtnOnclick(boolean addContactBtnOnclick) {
        this.addContactBtnOnclick = addContactBtnOnclick;
    }

    public boolean isAddAddressBtnOnclick() {
        return addAddressBtnOnclick;
    }

    public void setAddAddressBtnOnclick(boolean addAddressBtnOnclick) {
        this.addAddressBtnOnclick = addAddressBtnOnclick;
    }

    public boolean isAddPaymentBtnOnclick() {
        return addPaymentBtnOnclick;
    }

    public void setAddPaymentBtnOnclick(boolean addPaymentBtnOnclick) {
        this.addPaymentBtnOnclick = addPaymentBtnOnclick;
    }

    public Date getSixteenYearsOld() {
        return sixteenYearsOld;
    }

    public void setSixteenYearsOld(Date sixteenYearsOld) {
        this.sixteenYearsOld = sixteenYearsOld;
    }

}
