package performa.form;

import com.stripe.model.Subscription;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.business.content.Article;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.net.LoopbackHTTP;
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.ProcessRedirectResult;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import oneit.utils.MultiException;
import performa.orm.HiringTeam;
import performa.utils.StripeUtils;
import performa.utils.WebUtils;


public class SaveCompanyFP  extends SaveFP 
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request         =   submission.getRequest();
        HiringTeam          hiringTeam      =   (HiringTeam) process.getAttribute("HiringTeam");
        Boolean             isPayment       =   (Boolean) request.getAttribute("IsPayment");
        Subscription        subscription    =   StripeUtils.retrieveSubscription(hiringTeam.getStripeSubscription());
        Boolean             isHTLogoPresent =   process.getAttribute("IsHTLogoPresent") != null ? (Boolean) process.getAttribute("IsHTLogoPresent") : Boolean.FALSE;
        Article             article         =   WebUtils.getArticleByShortCut(process.getTransaction(), WebUtils.MY_COMPANY);
        String              nextPage        =   LoopbackHTTP.getRemoteAccessURL(request) 
                                                            + article.getLink(request, CollectionUtils.mapEntry("cms.rm", hiringTeam.getHiringTeamLogo() != null ? "Page" : "HiringTeam").toMap(), "/");

        if(CollectionUtils.equals(hiringTeam.getIsLogoDeleted(), Boolean.TRUE))
        {
            hiringTeam.setHiringTeamLogo(null);
            
            LogMgr.log(HiringTeam.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP setting hiring team logo to null of hiring team : ", hiringTeam );
        }
        
        if(hiringTeam.getManageOwnBilling())
        {
            hiringTeam.setBilledByTeam(null);
            
            if(hiringTeam.getStripeReference() == null)
            {
                StripeUtils.createCustomer(hiringTeam);
            
                LogMgr.log(HiringTeam.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP creating a customer in Stripe : ", hiringTeam );
            }
        }
        else
        {
            if(hiringTeam.getPaymentPlan() != null)
            {
                StripeUtils.cancelSubscription(subscription, true);
                
                hiringTeam.setUsedCredits(0);
                hiringTeam.setAvailableCredits(0);
                hiringTeam.setMaxCap(0);
                hiringTeam.setPaymentPlan(null);
                hiringTeam.setHasCap(false);
                
                LogMgr.log(HiringTeam.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP cancelling a subscription in Stripe since billing managed by another team: ", subscription );
            }
        }
        
        //Set attribute IsHTLogoPresent false when HT logo is not uploaded or deleted
        
        if(hiringTeam.getHiringTeamLogo() == null && !isHTLogoPresent)
        {
            process.setAttribute("IsHTLogoPresent", Boolean.FALSE);
            
            return new ProcessRedirectResult(nextPage, new String[]{});
        }
        
        process.setAttribute("nextPage", nextPage);
        process.setAttribute("HiringTeam", hiringTeam);
        
        return super.processForm(process, submission, params);
    }
    
    
    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
    {
        HttpServletRequest  request     =   submission.getRequest();
        HiringTeam          hiringTeam  =   (HiringTeam) process.getAttribute("HiringTeam");
        
        if(hiringTeam != null && !hiringTeam.getManageOwnBilling())
        {
            BusinessObjectParser.assertFieldCondition(hiringTeam.getBilledByTeam() != null, hiringTeam , HiringTeam.SINGLEREFERENCE_BilledByTeam, "mandatory", exceptions, true, request);
        }
        
        super.validate(process, submission, exceptions, params);
    }
}