package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.ObjectTransaction;
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.MultiException;
import performa.orm.Company;
import performa.orm.HiringTeam;


public class AddHiringTeamFP  extends SaveFP
{
    private static final LoggingArea  LOG =   LoggingArea.createLoggingArea("AddHiringTeamFP");
    
    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException 
    {
        HttpServletRequest  request     =   submission.getRequest();
        Company             company     =   (Company) process.getAttribute("Company");
        
        BusinessObjectParser.assertFieldCondition(company.getHiringTeamName() != null, company, Company.FIELD_HiringTeamName, "mandatory", exceptions, true, request);
        BusinessObjectParser.assertFieldCondition(company.getOwner() != null, company, Company.SINGLEREFERENCE_Owner, "mandatory", exceptions, true, request);

        if(!company.getManageOwnBilling())
        {
            BusinessObjectParser.assertFieldCondition(company.getBillingTeam() != null, company, Company.SINGLEREFERENCE_BillingTeam, "mandatory", exceptions, true, request);
        }
        
        super.validate(process, submission, exceptions, params);
    }


    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        ObjectTransaction   objTran     =   process.getTransaction();
        Company             company     =   (Company) process.getAttribute("Company");
        
        LogMgr.log(LOG, LogLevel.PROCESSING1, "Started to create new hiring team for company : ", company);

        HiringTeam hiringTeam   =   HiringTeam.createHiringTeam(objTran);

        hiringTeam.setHiringTeamName(company.getHiringTeamName());
        hiringTeam.setAddedByUser(company.getOwner());
        hiringTeam.setCompany(company);
        hiringTeam.setManageOwnBilling(company.getManageOwnBilling());
        
        if(hiringTeam.getManageOwnBilling())
        {
            hiringTeam.setBillingTeam(null);
        }
        else
        {
            hiringTeam.setBillingTeam(company.getBillingTeam());
        }
        
        LogMgr.log(LOG, LogLevel.PROCESSING1, "New hiring team created : ", hiringTeam);

        return super.processForm(process, submission, params);
    }
}