package performa.form;

import com.stripe.model.Subscription;
import java.util.Date;
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.orm.HiringTeam;
import performa.orm.PaymentPlan;
import performa.utils.StripeUtils;


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");
        PaymentPlan         paymentPlan =   (PaymentPlan) request.getAttribute("PaymentPlan");

        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 );
            }
        }
        
         
        if(hiringTeam.getIsPPJ())
        {
            Subscription    subscription    =   StripeUtils.retrieveSubscription(hiringTeam.getStripeSubscription());
            
            if(subscription != null)
            {
                StripeUtils.cancelSubscription(subscription);
                
                hiringTeam.setPaymentPlan(null);
                                
                LogMgr.log(HiringTeam.LOG, LogLevel.PROCESSING1,"In SaveCompanyFP cancelling a subscription in Stripe since moving to PPJ : ", subscription );

            }
        }
        
        if(CollectionUtils.equals(isPayment, Boolean.TRUE))
        {
            LogMgr.log(HiringTeam.LOG, LogLevel.PROCESSING1,"Hiring Team payment plan updated.", hiringTeam, " payment plan: ", hiringTeam.getPaymentPlan());

            if(hiringTeam.getCardID() == null)
            {
                throw new BusinessException("Please enter billing details before selecting a payment plan");
            }

            // cannot subscribe a user to a plan without card details
            Subscription    subscription        =   StripeUtils.retrieveSubscription(hiringTeam.getStripeSubscription());
            Subscription    updatedSubscription =   StripeUtils.updatePlan(hiringTeam, subscription, paymentPlan);

            if(updatedSubscription == null)
            {
                throw new BusinessException("Problem with changing your plan. Please contact adminstrator for more info.");
            }

            PaymentPlan currentPlan =   hiringTeam.getPaymentPlan();

            if(currentPlan != null && currentPlan.getActiveJobCount() < paymentPlan.getActiveJobCount())
            {
                boolean hasValidCoupon  =   hiringTeam.hasValidCouponOn(new Date(subscription.getCurrentPeriodEnd() * 1000));
                double  currentPlanCost =   hiringTeam.getLastPlanAmount() != null ? hiringTeam.getLastPlanAmount() : currentPlan.getAmount();
                double  newPlanCost     =   hasValidCoupon ?  paymentPlan.getAmount() * (1 - (hiringTeam.getCoupon().getPercentageOff() * 0.01)) : paymentPlan.getAmount();
                double  costDiff        =   newPlanCost - currentPlanCost;
                
                StripeUtils.chargeUpgradePlanDifference(hiringTeam, costDiff);
            }
            
            double  discountPercentage  =   0d;
            
            if(subscription.getDiscount() != null && subscription.getDiscount().getCoupon() != null && subscription.getDiscount().getCoupon().getPercentOff() != null)
            {
                discountPercentage  = 1 - (subscription.getDiscount().getCoupon().getPercentOff().doubleValue() * 0.01 );
            }

            hiringTeam.setLastPlanAmount(discountPercentage > 0 ?  paymentPlan.getAmount() * discountPercentage : paymentPlan.getAmount());
            

            if(currentPlan == null || currentPlan.getActiveJobCount() < paymentPlan.getActiveJobCount())
            {
                hiringTeam.setAvailableCredits(paymentPlan.getActiveJobCount());
            }

            hiringTeam.setPaymentPlan(paymentPlan);

            LogMgr.log(HiringTeam.LOG, LogLevel.PROCESSING1,"Stripe subscription updated.", hiringTeam, hiringTeam.getStripeSubscription());
        }
        
        if(!hiringTeam.isTrue(hiringTeam.getHasCap()))
        {
            hiringTeam.setMaxCap(null);
        }

        if(hiringTeam.isTrue(hiringTeam.getHasCap()) && hiringTeam.getPaymentPlan() != null)
        {
            if(hiringTeam.getMaxCap() == null)
            {
                hiringTeam.setMaxCap(hiringTeam.getPaymentPlan().getActiveJobCount());
            }
            else if(hiringTeam.getMaxCap() < hiringTeam.getPaymentPlan().getActiveJobCount())
            {
                throw new BusinessException("Cap should be greater than the number of jobs of the selected plan");
            }
        }
//        // 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();
        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);
    }
}