package performa.form;

import java.util.HashMap;
import java.util.Map;
import oneit.appservices.config.ConfigMgr;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.StringUtils;
import oneit.utils.math.NullArith;
import oneit.utils.parsers.FieldException;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import performa.orm.Job;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.Charge;
import com.stripe.model.Customer;
import com.stripe.model.Subscription;
import java.util.Calendar;
import java.util.Date;
import oneit.utils.DateDiff;


public class MakePaymentFP extends SaveFP
{

    public static final String  STRIPE_KEY      = ConfigMgr.getKeyfileString("stripe.key","");
    public static final String  STRIPE_PUB_KEY  = ConfigMgr.getKeyfileString("stripe.pubkey","");
    
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map p) throws BusinessException, StorageException
    {
        HttpServletRequest  request =   submission.getRequest();
        
        LogMgr.log(Job.LOG, LogLevel.PROCESSING1,"In MakePaymentFP : " );

        Stripe.apiKey = STRIPE_KEY;

        try
        {
            Customer customer = Customer.retrieve("cus_C8kIeItf64JnHe");
            System.out.println("customer :: " + customer);
        
//            Map<String, Object> item = new HashMap<>();
//            item.put("plan", "0001");
//
//            Map<String, Object> items = new HashMap<>();
//            items.put("0", item);
//
//            Map<String, Object> params = new HashMap<>();
//            params.put("items", items);
//            params.put("coupon", "EAP");
//            params.put("customer", "cus_C8kIeItf64JnHe");
//            
//            Date today = new Date(); 
//            Date trialExpiry = DateDiff.add(today, Calendar.DATE, 30);
//            
//            params.put("trial_end", trialExpiry.getTime() / 1000L);
//
//            Subscription subscription = Subscription.create(params);
//            
//            System.out.println("subscription : " + subscription);
        }
        catch(Exception e)
        {
        
        System.out.println("error occured : " +  e);
        }
//        performStripePayment(submission);

        
        return super.processForm(process, submission, p);
    }
    
    
    private void performStripePayment(SubmissionDetails submission) throws FieldException, BusinessException
    {
        HttpServletRequest  request                     = submission.getRequest();
        String              token                   = request.getParameter("stripe-token-id");
        
        if(StringUtils.subBlanks(token) == null)
        {
            throw new BusinessException("Stripe payment was failed, Please contact adminstrator for more info.");
        }
        
        Stripe.apiKey = STRIPE_KEY;

        // Charge the Customer instead of the card:
        Map<String, Object> chargeParams = new HashMap<String, Object>();
        chargeParams.put("amount", NullArith.intVal(NullArith.multiply(100d, 100, 0d)));
        chargeParams.put("currency", "aud");
        chargeParams.put("description", "Charges of creating job");
        chargeParams.put("source", token);
        Charge charge;
        try
        {
            charge = Charge.create(chargeParams);
        }
        catch (StripeException e)
        {
            throw new BusinessException("Stripe payment failure. Reason :: " + e.getMessage());
        }
        if(charge.getFailureCode() != null)
        {
            String errorMsg = "Stripe payment failure Code :: " + charge.getFailureCode() + ", Message :: " + charge.getFailureMessage();
            
            if(charge.getFraudDetails() != null)
            {
                errorMsg += ", Fraud Details :: " + charge.getFraudDetails();
            }
            
            
            throw new BusinessException(errorMsg);
        }
        
        System.out.println("stripe response : " + charge.toJson());
    }
}