package performa.form;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.StorageException;
import oneit.security.SecUser;
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.DateDiff;
import oneit.utils.math.NullArith;
import performa.orm.CompanyUser;
import performa.orm.HiringTeam;
import performa.orm.Job;
import performa.utils.StripeUtils;


public class ExtendJobFP extends SaveFP
{
    private static final LoggingArea  LOG =   LoggingArea.createLoggingArea("ExtendJobFP");

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        Job                 job         =   (Job) request.getAttribute("Job");
        HiringTeam          hiringTeam  =   job.getHiringTeam();
        HiringTeam          billingTeam =   hiringTeam.getManageOwnBilling() ? hiringTeam : hiringTeam.getBilledByTeam();
        SecUser             secUser     =   SecUser.getTXUser(process.getTransaction());
        CompanyUser         companyUser =   secUser.getExtension(CompanyUser.REFERENCE_CompanyUser);

        LogMgr.log(LOG, LogLevel.PROCESSING1, "Start of Extend job : ", job);

        
        job.setApplyBy(DateDiff.add(job.getApplyBy(), Calendar.DATE, 30));
        job.setLastEdited(new Date());

        if (billingTeam.canCreateJob())
        {
            billingTeam.setUsedCredits(NullArith.add(billingTeam.getUsedCredits(), 1).intValue());

            if(billingTeam.getUsedCredits() > billingTeam.getAvailableCredits())
            {
                StripeUtils.recordUsage(billingTeam);
            }
        }
        else if(billingTeam.getIsPPJ())
        {
            StripeUtils.makePayment(hiringTeam, job);
        }
        
        LogMgr.log(LOG, LogLevel.PROCESSING1, "Job Extended. Apply by date : ", job.getApplyBy());

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