package com.arrebol.taxiservicios.beans.topbar;

import com.arrebol.taxiservicios.beans.TaxiGenericBean;
import com.arrebol.taxiservicios.controller.login.LoginService;
import com.arrebol.taxiservicios.controller.notification.NotificationService;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.DeliveryStatusType;
import com.arrebol.taxiservicios.model.enums.StopNotificationType;
import com.arrebol.taxiservicios.model.notification.StopNotification;
import com.arrebol.taxiservicios.model.stocktaking.ServiceOrderNotification;
import com.arrebol.taxiservicios.wrapper.NotificationWrapper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
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 TopBarBean extends TaxiGenericBean implements Serializable {

    public void cleanAllNotificationsByUser() {
        try {
            getNotificationWrappers().clear();
            notificationService.cleanAllNotificationsByUser(getLoggedUser().getId());
            setTotalNotifications(0);
        } catch (Exception e) {
            logger.error("cleanAllNotificationsByUser", e);
        }
    }

    public void startStopNotification() {
        logger.debug("startStopNotification");

        try {
            setAutoStart(!isAutoStart());

            if (isAutoStart()) {
                notificationService.stopNotifiationByUser(getLoggedUser().getId(), null);
            } else {
                StopNotification notification = new StopNotification(UUID.randomUUID().toString(),
                        new User(getLoggedUser().getId(), ""), StopNotificationType.SERVICE_ORDER);
                notificationService.stopNotifiationByUser(getLoggedUser().getId(), notification);
            }
        } catch (Exception e) {
            logger.error("startStopNotification", e);
        }
    }

    public void getNotifications() {
        logger.debug("getNotifications");
        try {
            getNotificationWrappers().clear();
            setTotalNotifications(notificationService.countNotificationByUserId(getLoggedUser().getId()));

            if (getTotalNotifications() > 0) {
                List<ServiceOrderNotification> notification = notificationService.findNotificationDetailsByUserId(getLoggedUser().getId(), DeliveryStatusType.ENABLED);

                for (ServiceOrderNotification serviceOrderNotification : notification) {
                    getNotificationWrappers().add(new NotificationWrapper(serviceOrderNotification));
                }
            }
        } catch (Exception e) {
            setTotalNotifications(0);
            logger.error("count All Notifications ", e);
        }
    }

    public String getAvatar() {
        return getUser().getPerson().getAvatar();
    }

    private void loadUserDetails() {
        try {
            setUser(loginService.loadUserSigned(getLoggedUser().getUserName()));
            setLoggedUser(getUser());
        } catch (Exception e) {
            logger.error("No se pudo obtener los datos del usario logeado ", e);
        }
    }

    private static final long serialVersionUID = 9097210911560259149L;

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

    @Inject
    private NotificationService notificationService;

    @Inject
    private LoginService loginService;

    private User user;
    private List<NotificationWrapper> notificationWrappers;
    private int totalNotifications;
    private boolean autoStart;
    private String heightAutoScrollComponent;

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

            setAutoStart(notificationService.isActiveNotificationByUser(getLoggedUser().getId()));
        } catch (Exception e) {
            setUser(new User());
            showMessage(FacesMessage.SEVERITY_ERROR,
                    getBundlePropertyFile().getString("user.updated.address.title"),
                    getBundlePropertyFile().getString("user.update.address.fail.desc"));
        }
    }

    @PreDestroy
    public void destroy() {

    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<NotificationWrapper> getNotificationWrappers() {
        if (null == notificationWrappers) {
            notificationWrappers = new ArrayList<>();
        }
        return notificationWrappers;
    }

    public void setNotificationWrappers(List<NotificationWrapper> notificationWrappers) {
        this.notificationWrappers = notificationWrappers;
    }

    public int getTotalNotifications() {
        return totalNotifications;
    }

    public void setTotalNotifications(int totalNotifications) {
        this.totalNotifications = totalNotifications;
    }

    public boolean isAutoStart() {
        return autoStart;
    }

    public void setAutoStart(boolean autoStart) {
        this.autoStart = autoStart;
    }

    public String getHeightAutoScrollComponent() {
        if (getNotificationWrappers().isEmpty()) {
            heightAutoScrollComponent = "0px";
        } else if (getNotificationWrappers().size() == 1) {
            heightAutoScrollComponent = "50px";
        } else if (getNotificationWrappers().size() == 2) {
            heightAutoScrollComponent = "100px";
        } else {
            heightAutoScrollComponent = "145px";
        }

        return heightAutoScrollComponent;
    }

    public void setHeightAutoScrollComponent(String heightAutoScrollComponent) {
        this.heightAutoScrollComponent = heightAutoScrollComponent;
    }
}
