package com.arrebol.taxiservicios.beans.system;

import com.arrebol.car.driver.security.CarDriverSecurity;
import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.catalog.LocationController;
import com.arrebol.taxiservicios.controller.catalog.PaquetesController;
import com.arrebol.taxiservicios.controller.catalog.UserLocationController;
import com.arrebol.taxiservicios.controller.system.UserController;
import com.arrebol.taxiservicios.model.admin.ClosingDay;
import com.arrebol.taxiservicios.model.catalog.Location;
import com.arrebol.taxiservicios.model.catalog.LocationPaquetes;
import com.arrebol.taxiservicios.model.catalog.UserLocation;
import com.arrebol.taxiservicios.model.core.Person;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import com.arrebol.taxiservicios.model.enums.GenericEnumType;
import com.arrebol.taxiservicios.model.enums.UserStatusType;
import java.io.Serializable;
import java.math.BigDecimal;
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 Carlos Janitzio Zavala Lopez.
 */
@Named
@ViewScoped
public class UserBean extends TaxiGenericBean implements Serializable {

    public void createUser() {
        logger.info("createUser");
        try {
            //Se valida el número máximo de usuarios por locación
            List<User> users = getController().findUserActives(getLoggedUser().getLocation().getId());
             // Validación del paquete 
            setPaquetesController(new PaquetesController());
            List<LocationPaquetes> Lpack = getPaquetesController().fillAllLocationPaquetesByLocationAndEstatusActivo(new Location(getLocationId()), GenericEnumType.ENABLED);                 
            if (users.size() >= Lpack.get(0).getPaquete().getNumeroUsuarios()) {
                showMessage(FacesMessage.SEVERITY_ERROR, "Error", "Se ha alcanzado el número máximo de usuarios para el paquete asociado a locación seleccionada");
            } else if (validateData()) {
                User user = new User(UUID.randomUUID().toString(),
                        getUserName(), new CarDriverSecurity(APP, getPwd()).getPassword(),
                        Boolean.TRUE, getLoggedUser().getId());

                user.setUserStatusType(UserStatusType.ENABLED);
                user.setCreatedOn(new Date());

                if (getController().createUserByLocation(user, getEmployeeId(), getAvatar(), getLocationId())) {                    
                    logger.info("User created");
                    
                    // se crea un nuevo registro en UserLocation  
                    setUserLocationController(new UserLocationController());               
                    User us = getController().getById(user.getId());     
                    UserLocation usLo = new UserLocation();
                    usLo.setLocation(us.getLocation());
                    usLo.setUser(us);
                    usLo.setPagoAutomatico(0);
                    usLo.setEstatusActivo(GenericEnumType.ENABLED);
                    getUserLocationController().addUserLocation(usLo, getLoggedUser(), true);
                                        
                    clearFormAfterSuccessSubmit();
                    showMessage(FacesMessage.SEVERITY_INFO,
                            getBundlePropertyFile().getString("system.user.title"),
                            getBundlePropertyFile().getString("system.user.created.success"));

                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_MONTH, -2);

                    ClosingDay closingDay = new ClosingDay(
                            UUID.randomUUID().toString(),
                            user,
                            BigDecimal.ZERO,
                            BigDecimal.ZERO,
                            BasicType.ENEBLED,
                            "Se agrego corte de $0.00 automaticamente por el sistema cuando se creo el usuario",
                            getLoggedUser(),
                            calendar.getTime(),
                            new Location(getLocationId()));
                    if (!getController().addClosingDateToNewUser(closingDay)) {
                        showMessage(FacesMessage.SEVERITY_ERROR,
                                getBundlePropertyFile().getString("system.user.title"),
                                "No se pudo crear el corte del en $0.00 del usuario " + user.getUserName());
                    }
                } else {
                    logger.error("createUser");
                    showMessage(FacesMessage.SEVERITY_FATAL,
                            getBundlePropertyFile().getString("system.user.title"),
                            getBundlePropertyFile().getString("system.user.created.failure.desc"));
                }
            } else {
                logger.error("createUser");
                showMessage(FacesMessage.SEVERITY_ERROR,
                        getBundlePropertyFile().getString("system.user.title"),
                        getBundlePropertyFile().getString("system.user.validation.failure.desc"));
            }
        } catch (Exception e) {
            logger.error("Create user: " + e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("system.user.title"),
                    getBundlePropertyFile().getString("system.user.add.exception.desc"));
        }
    }

    public void availableUserName() {
        try {
            setUsernameMsg("");
            if (getUserName().trim().length() > 0) {
                if (!getController().availableUserName(getUserName().trim())) {
                    setFreeUserName(false);
                    setUsernameMsg("system.user.not.available");
                } else {
                    setFreeUserName(true);
                    setUsernameMsg("system.user.available");
                }
            }
        } catch (Exception e) {
            logger.error("Available Username: " + e);
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("system.user.title"),
                    getBundlePropertyFile().getString("system.user.exception.desc"));
        }
    }

    private boolean validateData() {
        boolean success = false;
        try {
            if (getPwd().trim().length() >= 5
                    && getPwd().equals(getPwdConfirm())
                    && getUserName().trim().length() > 3
                    && getController().availableUserName(getUserName().trim())
                    && null != getEmployeeId()
                    && !"".equals(getEmployeeId())) {
                success = true;
            }
        } catch (Exception e) {
            logger.error("Validate data: " + e);
        }
        return success;
    }

    private void clearFormAfterSuccessSubmit() {
        try {
            setEmployees(getController().getAllEmployeeWithoutUser());
            setUserName("");
            setEmployeeId("");
            setLocationId("");
            setAvatar(null);
        } catch (Exception e) {
            showMessage(FacesMessage.SEVERITY_INFO,
                    getBundlePropertyFile().getString("system.user.title"),
                    getBundlePropertyFile().getString("system.user.created.clean.form.failure"));
        }
    }

    private static final long serialVersionUID = -2896665425838021365L;

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

    private List<Person> employees;
    private List<Location> locations;
    private String employeeId;
    private String locationId;
    private UserController controller;
    private LocationController locationController;
    private String pwd;
    private String pwdConfirm;
    private String userName;
    private String avatar;
    private List<String> avatars;
    private boolean freeUserName;
    private String usernameMsg = "";
    private UserLocationController userLocationController;
    private List<UserLocation> listUserLocation;
    private PaquetesController paquetesController;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        try {
            setController(new UserController());
            setLocationController(new LocationController());
            setUserLocationController(new UserLocationController());
            setEmployees(getController().getAllEmployeeWithoutUser());
            setLocations(getLocationController().fillLocationDatatable());
            setListUserLocation(getUserLocationController().fillAllUserLocationByUser(getLoggedUser()));
        } catch (Exception e) {
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("system.user.title"),
                    getBundlePropertyFile().getString("fatal.access.details"));
        }

    }

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

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

    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<Person> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Person> employees) {
        this.employees = employees;
    }

    public String getEmployeeId() {
        return employeeId;
    }

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

    public UserController getController() {
        return controller;
    }

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

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getPwdConfirm() {
        return pwdConfirm;
    }

    public void setPwdConfirm(String pwdConfirm) {
        this.pwdConfirm = pwdConfirm;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAvatar() {
        if (null == avatar) {
            avatar = "images/unknown_user.png";
        }
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public UserLocationController getUserLocationController() {
        return userLocationController;
    }

    public void setUserLocationController(UserLocationController userLocationController) {
        this.userLocationController = userLocationController;
    }

    public List<UserLocation> getListUserLocation() {
        return listUserLocation;
    }

    public void setListUserLocation(List<UserLocation> listUserLocation) {
        this.listUserLocation = listUserLocation;
    }

    public List<String> getAvatars() {
        if (null == avatars) {
            avatars = new ArrayList<>();

            avatars.add("images/avatar/female-power/female-1.png");
            avatars.add("images/avatar/female-power/female-2.png");
            avatars.add("images/avatar/female-power/female-3.png");
            avatars.add("images/avatar/female-power/female-4.png");
            avatars.add("images/avatar/female-power/female-5.png");

            avatars.add("images/avatar/green-power/green-1.png");
            avatars.add("images/avatar/green-power/green-2.png");
            avatars.add("images/avatar/green-power/green-3.png");
            avatars.add("images/avatar/green-power/green-4.png");

            avatars.add("images/avatar/man-power/man-1.png");
            avatars.add("images/avatar/man-power/man-2.png");
            avatars.add("images/avatar/man-power/man-3.png");
            avatars.add("images/avatar/man-power/man-4.png");
            avatars.add("images/avatar/man-power/man-5.png");

            avatars.add("images/avatar/mask-power/mask-1.png");
            avatars.add("images/avatar/mask-power/mask-2.png");
            avatars.add("images/avatar/mask-power/mask-3.png");
            avatars.add("images/avatar/mask-power/mask-4.png");
        }
        return avatars;
    }

    public void setAvatars(List<String> avatars) {
        this.avatars = avatars;
    }

    public boolean isFreeUserName() {
        return freeUserName;
    }

    public void setFreeUserName(boolean freeUserName) {
        this.freeUserName = freeUserName;
    }

    public String getUsernameMsg() {
        return usernameMsg;
    }

    public void setUsernameMsg(String usernameMsg) {
        this.usernameMsg = usernameMsg;
    }

    public PaquetesController getPaquetesController() {
        return paquetesController;
    }

    public void setPaquetesController(PaquetesController paquetesController) {
        this.paquetesController = paquetesController;
    }

}
