package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import oneit.utils.MultiException;
import performa.intercom.utils.IntercomUtils;
import performa.orm.Company;


public class SaveCompanyFP  extends SaveFP 
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Company             company     =   process.getAttribute("Company") != null ? (Company) process.getAttribute("Company") : (Company) request.getAttribute("Company");
        Boolean             isPayment   =   (Boolean) request.getAttribute("IsPayment");

        LogMgr.log(Company.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP saving company : ", company );

        if(CollectionUtils.equals(company.getIsLogoDeleted(), Boolean.TRUE))
        {
            company.setCompanyLogo(null);
            
            LogMgr.log(Company.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP setting comany logo to null of company : ", company );
        }
        
        if(CollectionUtils.equals(isPayment, Boolean.TRUE) && company.getPaymentJobCount()!=null)
        {
            company.setPaymentPlan(company.getSelectedPaymentPlan());
            
            LogMgr.log(Company.LOG, LogLevel.PROCESSING1,"Company payment plan updated.", company, company.getPaymentPlan());
        }
        
        // Update company in intercom
        IntercomUtils.updateCompany(company);
        
        return super.processForm(process, submission, params);
    }
    
    
    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Company             company     =   process.getAttribute("Company") != null ? (Company) process.getAttribute("Company") : (Company) request.getAttribute("Company");
        Boolean             isPayment   =   (Boolean) request.getAttribute("IsPayment");
        
        //to select payment plan when job open
        if(CollectionUtils.equals(isPayment, Boolean.TRUE) && company.getPaymentJobCount()!=null)
        {
            BusinessObjectParser.assertFieldCondition(company.getSelectedPaymentPlan()!= null, company , Company.SINGLEREFERENCE_PaymentPlan, "mandatory", exceptions, true, request);
        }
        
        super.validate(process, submission, exceptions, params);
    }
}