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.PhoneType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
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("providerEditBean")
@ViewScoped
public class ProviderEditBean extends TaxiGenericBean implements Serializable {

    public void updateProvider() {
        logger.info("updateProvider");
        try {
            boolean success = getController().updatePersonById(
                    getProvider().getFirstName(), getProvider().getSecondName(),
                    getProvider().getLastName(), getProvider().getMiddleName(),
                    getProvider().getBirthdate(), getProvider().getId(),
                    getLoggedUser().getId(), null, getLoggedUser().getLocation().getId());

            if (success) {
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("provider.edit.title"),
                        getBundlePropertyFile().getString("provider.edit.success.desc"));
            } else {
                logger.error("Provider " + getProvider() + " was not updated");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("provider.edit.title"),
                        getBundlePropertyFile().getString("provider.edit.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("updateProvider: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("provider.edit.title"),
                    getBundlePropertyFile().getString("provider.edit.exception.desc"));
        }
    }

    public void editContactDetails() {
        logger.info("editContactDetails");
        try {
            boolean success = getController().saveOrUpdatePersonContactDetailsById(
                    getProviderId(), getProvider().getCurp(),
                    getProvider().getRfc(), getProvider().getMail(),
                    getContactNumbers(), getLoggedUser().getUserName(), isSaveLocalNumber(), isSaveMobile());

            if (success) {
                setSaveLocalNumber(false);
                setSaveMobile(false);
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("person.edit.contact.details.title"),
                        getBundlePropertyFile().getString("person.edit.contact.details.success.desc"));
            } else {
                logger.error("Employee " + getProvider() + " was not updated");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("person.edit.contact.details.title"),
                        getBundlePropertyFile().getString("person.edit.contact.details.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("editContactDetails: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("person.edit.contact.details.title"),
                    getBundlePropertyFile().getString("person.edit.contact.details.exception.desc"));
        }
    }

    /**
     *
     * @param formName
     */
    public void editAddress(String formName) {
        logger.info("editContactDetails");
        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"));
            */
            boolean success;
           if(isSaveAddress()){
            success = getController().saveOrUpdateAddress(getAddress(),
                    isSaveAddress(), getProviderId(), getLoggedUser().getUserName());
            }else{
            success = getController().updateAddress(address, getLoggedUser(), new Date());
            
            }
            if (success) {
                setSaveAddress(false);
                showMessage(FacesMessage.SEVERITY_INFO,
                        getBundlePropertyFile().getString("person.edit.address.title"),
                        getBundlePropertyFile().getString("person.edit.address.success.desc"));
            } else {
                logger.error("Customer " + getProvider() + " was not updated");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("person.edit.address.title"),
                        getBundlePropertyFile().getString("person.edit.address.fail.desc"));
            }
        } catch (Exception e) {
            logger.error("editContactDetails: " + e);
            showMessage(FacesMessage.SEVERITY_FATAL,
                    getBundlePropertyFile().getString("person.edit.address.title"),
                    getBundlePropertyFile().getString("person.edit.address.exception.desc"));
        }
    }

    private static final long serialVersionUID = -4201218847905362380L;

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

    private ProviderController controller;
    private String providerId;
    private Person provider;
    private List<ContactNumber> contactNumbers;
    private Address address;
    private Date sixteenYearsOld;
    private boolean saveMobile;
    private boolean saveLocalNumber;
    private boolean saveAddress;
    private LocationController locationController;
    private List<Location> locations;
    
    private ContactNumber phoneHome;
    private ContactNumber mobileHome;

    @PostConstruct
    public void init() {
        logger.info("init");
        try {
            loadBundlePropertyFile();

            Calendar calendar = Calendar.getInstance();

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

            setSixteenYearsOld(calendar.getTime());
            setController(new ProviderController());
            setProviderId(externalContext().getRequestParameterMap().get("providerForm:providerDtTbl_selection"));
            setProvider(getController().getPersonById(getProviderId()));
            //setContactNumbers(new ArrayList<ContactNumber>());
            
            setPhoneHome(getController().getContacNumberByIdPersonPhoneType(provider, PhoneType.HOME));
            setMobileHome(getController().getContacNumberByIdPersonPhoneType(provider, PhoneType.MOBILE));
            setLocationController(new LocationController());
            setLocations(getLocationController().fillLocationDatatable());

           setAddress(getController().getAddressByIdPerson(provider));

            if (null != getAddress()) {
                setSaveAddress(false);             
                           
            } else {
                setSaveAddress(true);
                setAddress(new Address(UUID.randomUUID().toString(), AddressType.HOME));
            }

            setContactNumbers(new ArrayList<ContactNumber>());
            if (null != getPhoneHome()) {
                
                     getContactNumbers().add(getPhoneHome());
           
                }else{
                    getContactNumbers().add(
                    null == phoneHome
                            ? new ContactNumber(UUID.randomUUID().toString(), PhoneType.HOME)
                            : phoneHome);
                }
            
            if (null != getMobileHome()) {
                
                     getContactNumbers().add(getMobileHome());
           
                }else{
                    getContactNumbers().add(
                    null == mobileHome
                            ? new ContactNumber(UUID.randomUUID().toString(), PhoneType.MOBILE)
                            : mobileHome);
                }
                
            setSaveLocalNumber(null == phoneHome);
            setSaveMobile(null == mobileHome);
            
        } catch (Exception e) {
            logger.info("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 String getProviderId() {
        return providerId;
    }

    public void setProviderId(String providerId) {
        this.providerId = providerId;
    }

    public Person getProvider() {
        return provider;
    }

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

    public List<ContactNumber> getContactNumbers() {
        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 Date getSixteenYearsOld() {
        return sixteenYearsOld;
    }

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

    public boolean isSaveMobile() {
        return saveMobile;
    }

    public void setSaveMobile(boolean saveMobile) {
        this.saveMobile = saveMobile;
    }

    public boolean isSaveLocalNumber() {
        return saveLocalNumber;
    }

    public void setSaveLocalNumber(boolean saveLocalNumber) {
        this.saveLocalNumber = saveLocalNumber;
    }

    public boolean isSaveAddress() {
        return saveAddress;
    }

    public void setSaveAddress(boolean saveAddress) {
        this.saveAddress = saveAddress;
    }

    public ContactNumber getPhoneHome() {
        return phoneHome;
    }

    public void setPhoneHome(ContactNumber phoneHome) {
        this.phoneHome = phoneHome;
    }

    public ContactNumber getMobileHome() {
        return mobileHome;
    }

    public void setMobileHome(ContactNumber mobileHome) {
        this.mobileHome = mobileHome;
    }

    
}
