/*
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
package com.arrebol.apc.model.admin;

import com.arrebol.apc.model.core.Office;
import com.arrebol.apc.model.core.User;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;

/**
 *
 * @author Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 */
@Table(name = "APC_OTHER_EXPENSE")
@Entity
public class OtherExpense implements Serializable {

    private static final long serialVersionUID = 6233701552847217683L;

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "id", length = 36)
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name = "id_user",
            referencedColumnName = "id",
            nullable = false
    )
    private User user;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(
            name = "id_office",
            referencedColumnName = "id",
            nullable = false
    )
    private Office office;

    @Column(name = "expense", nullable = false)
    private BigDecimal expense;

    @Column(name = "description", length = 200, nullable = false)
    private String description;

    @Column(name = "created_by", nullable = false, length = 36)
    private String createdBy;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name = "created_by",
            referencedColumnName = "id",
            nullable = false,
            insertable = false,
            updatable = false
 
    )
    private User userCreatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_on", length = 19)
    private Date createdOn;

    @Column(name = "last_updated_by", length = 36)
    private String lastUpdatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "last_updated_on", length = 19)
    private Date lastUpdatedOn;

    public OtherExpense() {
    }

    /**
     *
     * @param officeId
     * @param userId
     * @param expense
     * @param description
     */
    public OtherExpense(String officeId, String userId, BigDecimal expense, String description) {
        this.office = new Office(officeId);
        this.user = new User(userId);
        this.expense = expense;
        this.description = description;
        this.createdBy = userId;
        this.createdOn = new Date();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public User getUser() {
        return user;
    }

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

    public Office getOffice() {
        return office;
    }

    public void setOffice(Office office) {
        this.office = office;
    }

    public BigDecimal getExpense() {
        return expense;
    }

    public void setExpense(BigDecimal expense) {
        this.expense = expense;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }

    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(String lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    public Date getLastUpdatedOn() {
        return lastUpdatedOn;
    }

    public void setLastUpdatedOn(Date lastUpdatedOn) {
        this.lastUpdatedOn = lastUpdatedOn;
    }

    public String getUserRoutes() {
        String routes = "";
        routes = user.getHumanResource().getHumanResourceHasRoutes().stream().map((py) -> py.getRouteCtlg().getRoute()).collect(Collectors.joining(", "));

        return routes;
    }
    
    public User getUserCreatedBy() {
        return userCreatedBy;
    }

    public void setUserCreatedBy(User userCreatedBy) {
        this.userCreatedBy = userCreatedBy;
    }
    
    public String getCreatedByName() {
        String name = getUserCreatedBy().getHumanResource().getFirstName() + " " + getUserCreatedBy().getHumanResource().getLastName();

        return name;
    }
    
    public boolean getAction(Date lastStableSmallBox, List<ClosingDay> closingDayToday) {
        Date date = createdOn;
        String closingDayUser = null;
        boolean action = true;
        try {
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");

            String dateStr = dt1.format(date);
            date = dt1.parse(dateStr);

            action = date.after(lastStableSmallBox);
            
            // Busca el corte del día de este usuario
            if (closingDayToday != null) {
                Optional<ClosingDay> optUser = closingDayToday.stream().filter(p -> p.getUser().getId().equalsIgnoreCase(user.getId())
                 && p.getCreatedOn().equals(createdOn)).findFirst();
                closingDayUser = optUser.isPresent() ? optUser.get().getId(): null;
                
                String dateStrCD;
                Date dateCD;
                for(ClosingDay dato : closingDayToday){
                    dateStrCD = dt1.format(dato.getCreatedOn());
                    dateCD = dt1.parse(dateStrCD);
                    
                    if(dato.getUser().getId().equalsIgnoreCase(getUser().getId()) && dateCD.equals(date)){
                        closingDayUser = dato.getUser().getId();
                    }
                }
            }
            
            if(action){
                if(closingDayUser != null){
                    action = false;
                }
            }

        } catch (ParseException ex) {
            Logger.getLogger(ExpenseCompany.class.getName()).log(Level.SEVERE, null, ex);
        }
        return action;
    }
    
    @Override
    public String toString() {
        return "OtherExpense{" + "description=" + description + ", createdOn=" + createdOn + '}';
    }

}
