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

import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.admin.EmployeeController;
import com.arrebol.taxiservicios.controller.catalog.LocationController;
import com.arrebol.taxiservicios.model.admin.Document;
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.core.User;
import com.arrebol.taxiservicios.model.enums.AddressType;
import com.arrebol.taxiservicios.model.enums.DocumentType;
import com.arrebol.taxiservicios.model.enums.PaymentType;
import com.arrebol.taxiservicios.model.enums.PhoneType;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
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;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

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

   public void editEmployee() {
      logger.info("editEmployee");
      try {
         boolean success = getController().updatePersonById(
                 getEmployee().getFirstName(), getEmployee().getSecondName(),
                 getEmployee().getLastName(), getEmployee().getMiddleName(),
                 getEmployee().getBirthdate(), getEmployee().getAdmissionDate(),
                 getEmployee().getId(), getLoggedUser().getUserName(), locationId,
                 getEmployee().getSalary(), getEmployee().getImss(),
                 getEmployee().getSavingWeek());

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

   public void editContactDetails() {
      logger.info("editContactDetails");
      try {
         boolean success = getController().saveOrUpdatePersonContactDetailsById(
                 getEmployeeId(), getEmployee().getCurp(),
                 getEmployee().getRfc(), getEmployee().getMail(),
                 getNumbers(), 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 " + getEmployee() + " 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"));
      }
   }

   public void editAddress(String formName) {
      logger.info("editAddress");
      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(), getEmployeeId(), 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("Employee " + getEmployee() + " 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("editAddress: " + e);
         showMessage(FacesMessage.SEVERITY_FATAL,
                 getBundlePropertyFile().getString("person.edit.address.title"),
                 getBundlePropertyFile().getString("person.edit.address.exception.desc"));
      }
   }

   /**
    *
    */
   public void editPayment() {
      logger.info("editPayment");
      try {
         boolean success = getController().updateEmployeePaymentDetailsById(
                 getEmployee().getPayment(), getEmployee().getPaymentType(),
                 getEmployeeId(), getLoggedUser().getUserName());

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

   public void handleFileUpload(FileUploadEvent event) {
      logger.info("handleFileUpload.");
      try {
         UploadedFile file = event.getFile();

         List<Document> documents = new ArrayList<Document>();

         getDocument().setPath(file.getContentType());
         getDocument().setFileName(file.getFileName());
         getDocument().setContent(file.getContents());

         if (isSavePhotoBtnOnclick()) {
            getDocument().setId(UUID.randomUUID().toString());
            getDocument().setPerson(new Person(getEmployeeId()));
            getDocument().setCreatedBy(new User(getLoggedUser().getId(), ""));
         } else {
            getDocument().setLastUpdatedBy(new User(getLoggedUser().getId(), ""));
         }

         documents.add(getDocument());

         boolean success = getController().saveOrUpdatePhotos(documents, isSavePhotoBtnOnclick());

         if (success) {
            setSavePhotoBtnOnclick(false);
            setPhotoName(getBundlePropertyFile().getString("document.title")
                    + " " + file.getFileName()
                    + " " + getBundlePropertyFile().getString("driver.document.update.success.desc"));

            logger.info("Employee photo updated.");
            showMessage(FacesMessage.SEVERITY_INFO,
                    getBundlePropertyFile().getString("person.edit.photo.title"),
                    getBundlePropertyFile().getString("person.edit.photo.success.desc"));
         } else {
            setPhotoName(getBundlePropertyFile().getString("document.title")
                    + " " + file.getFileName()
                    + " " + getBundlePropertyFile().getString("driver.document.add.fail.desc"));

            logger.error("Employee photo not updated " + getDocument());
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("person.edit.photo.title"),
                    getBundlePropertyFile().getString("person.edit.photo.fail.desc"));
         }
      } catch (Exception e) {
         logger.error("handleFileUpload: " + e);

         setPhotoName(getBundlePropertyFile().getString("document.exception.desc"));
         showMessage(FacesMessage.SEVERITY_FATAL,
                 getBundlePropertyFile().getString("person.edit.photo.title"),
                 getBundlePropertyFile().getString("person.edit.photo.exception.desc"));
      }
   }

   private static final long serialVersionUID = 6561677148166677732L;

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

   private EmployeeController controller;
   private LocationController locationController;
   private String locationId;
   private List<Location> locations;
   private String employeeId;
   private Person employee;
   private List<ContactNumber> numbers;
   private Address address;
   private Date sixteenYearsOld;
   private List<PaymentType> paymentTypes;
   private PaymentType paymentType;
   private boolean saveMobile;
   private boolean saveLocalNumber;
   private boolean saveAddress;
   private Document document;
   private String photoName;
   private boolean savePhotoBtnOnclick;
   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 EmployeeController());
         setLocationController(new LocationController());
         setLocations(getLocationController().fillLocationDatatable());
         setLocationId(locationId);
         setEmployeeId(externalContext().getRequestParameterMap().get("employeeForm:employeesDtTbl_selection"));
         setEmployee(getController().getPersonById(getEmployeeId()));
         //setNumbers(getController().getContactNumberByIdPerson(employee));
         setPhoneHome(getController().getContacNumberByIdPersonPhoneType(employee, PhoneType.HOME));
         setMobileHome(getController().getContacNumberByIdPersonPhoneType(employee, PhoneType.MOBILE));
         setLocationId(getEmployee().getLocation().getId());
         getPaymentTypes().addAll(Arrays.asList(PaymentType.values()));

         setAddress(getController().getAddressByIdPerson(employee));

         if (null != getAddress()) {
            setSaveAddress(false);

         } else {
            setSaveAddress(true);
            setAddress(new Address(UUID.randomUUID().toString(), AddressType.HOME));
         }

         if (null != getEmployee().getPaymentType()) {
            setPaymentType(getEmployee().getPaymentType());
         }

         setNumbers(new ArrayList<ContactNumber>());
         if (null != getPhoneHome()) {

            getNumbers().add(getPhoneHome());

         } else {
            getNumbers().add(
                    null == phoneHome
                            ? new ContactNumber(UUID.randomUUID().toString(), PhoneType.HOME)
                            : phoneHome);
         }

         if (null != getMobileHome()) {

            getNumbers().add(getMobileHome());

         } else {
            getNumbers().add(
                    null == mobileHome
                            ? new ContactNumber(UUID.randomUUID().toString(), PhoneType.MOBILE)
                            : mobileHome);
         }

         setSaveLocalNumber(null == phoneHome);
         setSaveMobile(null == mobileHome);
         if (null != getEmployee().getDocuments() && !getEmployee().getDocuments().isEmpty()) {
            ((Set<Document>) getEmployee().getDocuments()).forEach((Document doc) -> {
               setDocument(doc);
               setPhotoName(getBundlePropertyFile().getString("document.title")
                       + " " + doc.getFileName()
                       + " " + getBundlePropertyFile().getString("driver.document.add.success.desc"));
            });
         } else {
            setSavePhotoBtnOnclick(true);
            setDocument(new Document(DocumentType.SELFIE));
         }
      } catch (Exception e) {
         logger.info("init", e);
      }
   }

   public LocationController getLocationController() {
      return locationController;
   }

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

   public String getLocationId() {
      return locationId;
   }

   public void setLocationId(String locationId) {
      this.locationId = locationId;
   }

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

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

   public EmployeeController getController() {
      return controller;
   }

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

   public String getEmployeeId() {
      return employeeId;
   }

   public void setEmployeeId(String employeeId) {
      this.employeeId = employeeId;
   }

   public Person getEmployee() {
      return employee;
   }

   public void setEmployee(Person employee) {
      this.employee = employee;
   }

   public List<ContactNumber> getNumbers() {
      return numbers;
   }

   public void setNumbers(List<ContactNumber> numbers) {
      this.numbers = numbers;
   }

   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 List<PaymentType> getPaymentTypes() {
      if (null == paymentTypes) {
         paymentTypes = new ArrayList<PaymentType>();
      }
      return paymentTypes;
   }

   public void setPaymentTypes(List<PaymentType> paymentTypes) {
      this.paymentTypes = paymentTypes;
   }

   public PaymentType getPaymentType() {
      return paymentType;
   }

   public void setPaymentType(PaymentType paymentType) {
      this.paymentType = paymentType;
   }

   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 Document getDocument() {
      return document;
   }

   public void setDocument(Document document) {
      this.document = document;
   }

   public String getPhotoName() {
      return photoName;
   }

   public void setPhotoName(String photoName) {
      this.photoName = photoName;
   }

   public boolean isSavePhotoBtnOnclick() {
      return savePhotoBtnOnclick;
   }

   public void setSavePhotoBtnOnclick(boolean savePhotoBtnOnclick) {
      this.savePhotoBtnOnclick = savePhotoBtnOnclick;
   }

   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;
   }

}
