/*
 * 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.apc.web.beans.admin;

import com.arrebol.apc.controller.GenericController;
import com.arrebol.apc.controller.admin.LoanController;
import com.arrebol.apc.controller.catalog.LoanTypeController;
import com.arrebol.apc.controller.catalog.RouteController;
import com.arrebol.apc.controller.util.DateWrapper;
import com.arrebol.apc.model.catalog.RouteCtlg;
import com.arrebol.apc.model.core.User;
import com.arrebol.apc.model.enums.ActiveStatus;
import com.arrebol.apc.model.enums.FeeStatus;
import com.arrebol.apc.model.enums.LoanDetailsType;
import com.arrebol.apc.model.enums.LoanStatus;
import com.arrebol.apc.model.enums.PeopleType;
import com.arrebol.apc.model.enums.TransferStatus;
import com.arrebol.apc.model.loan.Loan;
import com.arrebol.apc.model.loan.LoanDetails;
import com.arrebol.apc.model.loan.LoanFeeNotification;
import com.arrebol.apc.web.beans.Datatable;
import com.arrebol.apc.web.beans.GenericBean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import org.primefaces.event.ReorderEvent;
import org.primefaces.event.RowEditEvent;

/**
 *
 * @author Oscar
 */

@Named("loanDetailTransferManager")
@ViewScoped
public class LoanDetailTransferBean extends GenericBean implements Serializable, Datatable  {
    

    public List<LoanDetails> fillDatatableLoan() {
        return getLoanCtrl().fillAllTransfersLoanDetails();
    }


    public void authorizeLoanDetail(){
        getLoanCtrl().updateAuthorizeLoanDetailById(selectedLoanDetails.getId());
        
        showMessage(FacesMessage.SEVERITY_INFO, "Deposito validado", "El depostio fue autorizado.");
        setLoanDetails(fillDatatableLoan());
           
    }
    
    
    public void rejectLoanDetail(){
        getLoanCtrl().updateRejectLoanDetailById(selectedLoanDetails.getId());
        
        showMessage(FacesMessage.SEVERITY_INFO, "Deposito validado", "El depostio fue rechazado.");
        
        
        LoanDetails detail = new LoanDetails();
        Loan loan = selectedLoanDetails.getLoan();
        detail.setComments("Transferencia cancelada");
        detail.setCreatedBy(getLoggedUser().getUser().getId());
        detail.setCreatedOn(new Date());
        detail.setLoan(loan);
        detail.setLoanDetailsType(LoanDetailsType.FEE);
        detail.setTransferStatus(TransferStatus.AUTHORIZED);
        detail.setTransferNumber("N/A");
        detail.setFeeStatus(FeeStatus.TO_PAY);
        detail.setPaymentAmount(loan.getLoanType().getFee());
        detail.setPeopleType(PeopleType.CUSTOMER);
        detail.setReferenceNumber(selectedLoanDetails.getLoan().getLastReferenceNumber() + 1);
        detail.setUser(selectedLoanDetails.getUser());
        if (loanCtrl.saveLoanDetail(detail)) {
            Loan loanUpdate = loanCtrl.getLoanById(loan.getId());
            loanUpdate.setAmountToPay(loanUpdate.getAmountToPay().add(loan.getLoanType().getFee()));
            loanUpdate.setAmountPaid(loanUpdate.getAmountPaid().subtract(selectedLoanDetails.getPaymentAmount()));
            loanUpdate.setLastUpdatedOn(new Date());
            loanUpdate.setLastUpdatedBy(getLoggedUser().getUser().getId());
            loanUpdate.setLastReferenceNumber(loanUpdate.getLastReferenceNumber() + 1);
            loanCtrl.updateLoan(loanUpdate);

            LoanFeeNotification notification = new LoanFeeNotification();
            notification.setCreatedBy(getLoggedUser().getUser().getId());
            notification.setCreatedOn(new Date());
            notification.setLoan(loanUpdate);
            notification.setUser(selectedLoanDetails.getUser());
            notification.setNotificationNumber(loanUpdate.getTotalFeeByLoan() + 1);
            loanCtrl.saveLoanNotificationFee(notification);

          
            showMessage(FacesMessage.SEVERITY_INFO, "Multa creada", "Se creo la multa de forma correcta.");
        }
        setLoanDetails(fillDatatableLoan());
           
    }
    public void deleteLoan() {
        /*    loanCtrl.updateLoanByStatusWeb(LoanStatus.DELETED, selectedLoan.getId(), getLoggedUser().getUser().getId());
        loanCtrl.updateLoanByUserByStatus(LoanStatus.DELETED, selectedLoan);
        loan.remove(selectedLoan);
        selectedLoan = null;

        showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "El prÃ©stamo se cambiÃ³ a estatus 'Eliminado' de forma correcta.");*/
    }

    public void changeApprovedStatus() {
        /*loanCtrl.updateLoanByStatusWeb(LoanStatus.APPROVED, selectedLoan.getId(), getLoggedUser().getUser().getId());
        loanCtrl.updateLoanByUserByStatus(LoanStatus.APPROVED, selectedLoan);
        loan.clear();
        loan = fillDatatableLoan();
        selectedLoan = null;

        showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "El prÃ©stamo se cambiÃ³ a estatus 'Aprobado' de forma correcta.");*/
    }

    public void changeFinishStatus() {
        /*loanCtrl.updateLoanByStatusWeb(LoanStatus.FINISH, selectedLoan.getId(), getLoggedUser().getUser().getId());
        loanCtrl.updateLoanByUserByStatus(LoanStatus.FINISH, selectedLoan);
        loan.clear();
        loan = fillDatatableLoan();
        selectedLoan = null;

        showMessage(FacesMessage.SEVERITY_INFO, "Cambio de estatus", "El prÃ©stamo se cambiÃ³ a estatus 'Aprobado' de forma correcta.");*/
    }

    public void deletePaymentLoan() {

        /*if (selectedLoan.getLoanStatus() == LoanStatus.APPROVED || selectedLoan.getLoanStatus() == LoanStatus.PENDING_RENOVATION) {
            
            List<LoanDetails> details = loanCtrl.getLoanDetailsCurdatebyIdLoan(selectedLoan.getId());
        if (details != null && !details.isEmpty()) {
            Loan loanUpdate = loanCtrl.getLoanById(selectedLoan.getId());
            for (LoanDetails detail : details) {
                loanUpdate.setAmountPaid(loanUpdate.getAmountPaid().subtract(detail.getPaymentAmount()));
                loanUpdate.setLastReferenceNumber(loanUpdate.getLastReferenceNumber() - 1);
            }
            if (loanCtrl.deleteLoanDetailsByLoanCurdate(selectedLoan)) {
                loanCtrl.updateLoan(loanUpdate);
                loan.clear();
                loan = fillDatatableLoan();
                selectedLoan = null;
                showMessage(FacesMessage.SEVERITY_INFO, "Abonos eliminados", "Se eliminÃ³ el/los abonos del dÃ­a de hoy correctamente.");
            }
        } else {
            showMessage(FacesMessage.SEVERITY_WARN, "Advertencia", "El prÃ©stamo no tiene registrado abonos el dÃ­a de hoy");
        }
        }
        else
        {
           showMessage(FacesMessage.SEVERITY_WARN, "No se puede eliminar abono", "Solo puedes eliminar el abono de prÃ©stamos en estatus Aprobados o Pendiente por renovaciÃ³n");
            return; 
        }*/
    }

    @Override
    public void editRow(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
    }

    @Override
    public void onRowCancel(RowEditEvent event) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void onRowReorder(ReorderEvent event) {
        showMessage(FacesMessage.SEVERITY_INFO, "Registro Movido", "De columna: " + (event.getFromIndex() + 1) + " a columna: " + (event.getToIndex() + 1));
    }

    @Override
    public void addRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deleteRow() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    /**
     *
     * @param outcome
     * @return
     */
    public String detailLoan(String outcome) {
        return outcome;
    }

    public LoanController getLoanCtrl() {
        return loanCtrl;
    }

    public void setLoanCtrl(LoanController loanCtrl) {
        this.loanCtrl = loanCtrl;
    }

    public List<LoanDetails> getLoanDetails() {
        return loanDetails;
    }

    public void setLoanDetails(List<LoanDetails> loanDetails) {
        this.loanDetails = loanDetails;
    }

    public LoanDetails getSelectedLoanDetails() {
        return selectedLoanDetails;
    }

    public void setSelectedLoanDetails(LoanDetails selectedLoanDetails) {
        this.selectedLoanDetails = selectedLoanDetails;
    }

    

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public GenericController getGenericCtrl() {
        return genericCtrl;
    }

    public void setGenericCtrl(GenericController genericCtrl) {
        this.genericCtrl = genericCtrl;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public BigDecimal getPayment() {
        return payment;
    }

    public void setPayment(BigDecimal payment) {
        this.payment = payment;
    }

    public BigDecimal getFee() {
        return fee;
    }

    public void setFee(BigDecimal fee) {
        this.fee = fee;
    }

    public LoanTypeController getLoanTypeCtrl() {
        return loanTypeCtrl;
    }

    public void setLoanTypeCtrl(LoanTypeController loanTypeCtrl) {
        this.loanTypeCtrl = loanTypeCtrl;
    }

    public String getLoanTypeId() {
        return loanTypeId;
    }

    public void setLoanTypeId(String loanTypeId) {
        this.loanTypeId = loanTypeId;
    }

    public String getRouteId() {
        return routeId;
    }

    public void setRouteId(String routeId) {
        this.routeId = routeId;
    }

    public RouteController getRouteCtrl() {
        return routeCtrl;
    }

    public void setRouteCtrl(RouteController routeCtrl) {
        this.routeCtrl = routeCtrl;
    }

    private LoanController loanCtrl;
    private LoanTypeController loanTypeCtrl;
    private GenericController genericCtrl;
    private RouteController routeCtrl;

    private List<LoanDetails> loanDetails;
    private List<User> users;
    private LoanDetails selectedLoanDetails;
    private String comments;
    private String userId;
    private BigDecimal payment;
    private BigDecimal fee;
    private String loanTypeId;
    private String routeId;

    @PostConstruct
    public void init() {
        loadBundlePropertyFile();
        
        loanCtrl = new LoanController();
        genericCtrl = new GenericController();
        loanTypeCtrl = new LoanTypeController();
        routeCtrl = new RouteController();
        users = genericCtrl.getAllUsersByOffice(getLoggedUser().getOffice().getId());

        setLoanDetails(fillDatatableLoan());
    }

}
