package performa.orm;

import com.stripe.model.Card;
import oneit.logging.LoggingArea;
import oneit.objstore.ObjectStatus;
import oneit.objstore.ValidationContext;
import oneit.objstore.rdbms.filters.EqualsFilter;
import oneit.security.SecUser;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import oneit.utils.StringUtils;
import oneit.utils.math.NullArith;
import oneit.utils.parsers.FieldException;
import performa.orm.types.JobStatus;
import performa.utils.StripeUtils;
import performa.utils.Utils;


public class Company extends BaseCompany
{
    private static final long serialVersionUID = 0L;
    
    public  static LoggingArea  LOG = LoggingArea.createLoggingArea("Company");

    // This constructor should not be called
    public Company ()
    {
        // Do not add any code to this, always put it in initialiseNewObject
    }

    @Override
    protected void postInitNewObj() throws BusinessException 
    {
        addToHiringTeams(HiringTeam.createHiringTeam(getTransaction()));

        super.postInitNewObj();
    }
    
    
    public boolean showHasClientSupport()
    {
        return isTrue(getHasClientSupport());
    }
    
    public boolean showTeamManagesOwnBilling()
    {
        return isTrue(getManageOwnBilling());
    }
    
    //This logic moved from invite_users.jsp
    public boolean createDefaultUser() throws FieldException
    {
        boolean addUser =   true;
        for (CompanyUser cUser : getUsersSet())
        {
            if(!CollectionUtils.equals(cUser, getAddedByUser()))
            {
                addUser =   false;
            }
        }
        
        if(addUser)
        {
            SecUser     secUser     =   SecUser.createSecUser(getTransaction());
            CompanyUser companyUser =   secUser.getExtensionOrCreate(CompanyUser.REFERENCE_CompanyUser);
        
            addToUsers(companyUser);
        }
        return addUser;
    }

    
    public Boolean isEmailCorrect()
    {
        return StringUtils.isEmailAddress(StringUtils.subBlanks(getUserEmail()));
    }
    
    
    @Override
    public String getToString() 
    {
        return StringUtils.subNulls(getCompanyName(), super.getToString());
    }
    
    
    public PaymentPlan getSelectedPaymentPlan()
    {
        if(getPaymentJobCount() != null)
        {
            PaymentPlan maxPlan =   Utils.getMaximumPaymentPlan(getTransaction());
            
            if(maxPlan!=null && getPaymentJobCount()>=maxPlan.getActiveJobCount())
            {
                return maxPlan;
            }
            
            PaymentPlan[]   plans   =   PaymentPlan.SearchByAll()
                                                .andActiveJobCount(new EqualsFilter<>(getPaymentJobCount()))
                                                .search(getTransaction());
            
            if(plans.length > 0)
            {
                return plans[0];
            }
        }
        
        return null;
    }
    
    
    public Double getPaymentPlanAmount()
    {
        PaymentPlan selectedPaymentPlan =   getSelectedPaymentPlan();
        
        if(selectedPaymentPlan!=null)
        {
            return selectedPaymentPlan.getAmount();
        }
        
        return null;
    }
   
    
    public Double getPerJobPaymentPlanAmount()
    {
        PaymentPlan selectedPaymentPlan =   getSelectedPaymentPlan();
        
        if(selectedPaymentPlan!=null)
        {
            return NullArith.divide(selectedPaymentPlan.getAmount(), selectedPaymentPlan.getActiveJobCount());
        }
        
        return null;
    }
    
    
    public Double getPaymentPlanSaveAmount()
    {
        PaymentPlan selectedPaymentPlan =   getSelectedPaymentPlan();
        
        if(selectedPaymentPlan!=null)
        {
            return selectedPaymentPlan.getPerMonthSaveAmount();
        }
        
        return null;
    }
    
    
    public boolean canCreateJob()
    {        
        return getPaymentPlan() != null && getPaymentPlan().getActiveJobCount() > getUsedCredits();
    }

    
    @Override
    public Integer getUsedCredits() 
    {
        return super.getUsedCredits()  != null ? super.getUsedCredits() : 0;
    }

    
    public Job[] getOpenJobs()
    {
        return  Job.SearchByCompany()
                    .andJobStatus(new EqualsFilter<>(JobStatus.OPEN))
                    .byCompany(this)
                    .search(getTransaction());
    }
    
    
    public Integer getOpenJobsCount()
    {
        return getOpenJobs().length;
    }

    
    public Card getCard() throws FieldException
    {
       return StripeUtils.retrieveCard(this);
    }
    
    
    public String getCardNumber() throws FieldException
    {
        if(getStripeLast4() == null)
        {
            Card    card    =   StripeUtils.retrieveCard(this);
            
            if(card != null)
            {
                setStripeLast4(card.getLast4());
                setStripeBrand(card.getBrand());
                
                return "xxxx-xxxx-xxxx-" + getStripeLast4();
            }
            else
            {
                return "";
            }
        }
        
        return "xxxx-xxxx-xxxx-" + getStripeLast4();
    }
    
    
    public String getExpiry () throws FieldException
    {
        Card    card    =   StripeUtils.retrieveCard(this);

        return card != null ? String.format("%02d", card.getExpMonth()) + " / " + (card.getExpYear() % 100) : "";
    }
    
    
    public Boolean isSubscriptionChanged()
    {
        PaymentPlan selectedPaymentPlan =   getSelectedPaymentPlan();
        
        if(selectedPaymentPlan!=null)
        {    
            Company earliestBackup  =   (Company) getEarliestBackup();
            
            if(!CollectionUtils.equals(earliestBackup.getPaymentPlan(), selectedPaymentPlan))
            {
                return Boolean.TRUE;
            }
        }
        
        return Boolean.FALSE;
    }
    
    public HiringTeam getDefaultHiringTeam()
    {
        return getHiringTeamsCount() > 0 ? getHiringTeamsAt(0) : null;
    }
}