package performa.form;

import com.stripe.Stripe;
import com.stripe.exception.APIConnectionException;
import com.stripe.exception.APIException;
import com.stripe.exception.AuthenticationException;
import com.stripe.exception.CardException;
import com.stripe.exception.InvalidRequestException;
import com.stripe.model.Card;
import java.util.HashMap;
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.parsers.FieldException;
import performa.orm.Company;
import performa.orm.CompanyUser;
import performa.utils.StripeUtils;


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

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map p) throws BusinessException, StorageException
    {

        Stripe.apiKey = StripeUtils.STRIPE_KEY;
            
        updateCardDetails(process, submission);

        return super.processForm(process, submission, p);
    }
    
    
    public static void updateCardDetails(ORMProcessState process, SubmissionDetails submission) throws FieldException
    {
        try
        {
            HttpServletRequest  request =   submission.getRequest();

            SecUser     secUser     =   SecUser.getTXUser(process.getTransaction());
            CompanyUser companyUser =   secUser.getExtension(CompanyUser.REFERENCE_CompanyUser);
            Company     company     =   companyUser.getCompany();
            Card        card        =   StripeUtils.retrieveCard(company);

            LogMgr.log(LOG, LogLevel.PROCESSING1,"In UpdateCardFP updating card details of user : ", company, " card : " , card );

            Map<String, Object> updateParams    =   new HashMap<>();
            String              expiryDate      = request.getParameter("expiry-date");
            String              name            = request.getParameter("holder-name");
            String              addressZip      = request.getParameter("address-zip");

            if(expiryDate != null && !expiryDate.isEmpty() && expiryDate.length() == 7)
            {
                updateParams.put("exp_month", expiryDate.substring(0, 2));
                updateParams.put("exp_year", expiryDate.substring(5, 7));
            }

            if(name != null && !name.isEmpty())
            {
                updateParams.put("name", name);
                company.setNameOnCard(name);
            }
            
            if(addressZip != null && !addressZip.isEmpty())
            {
                updateParams.put("address_zip", addressZip);
                company.setCardPostCode(addressZip);
            }
            
            Card    updatedCard =   card.update(updateParams);


            LogMgr.log(LOG, LogLevel.PROCESSING1,"Updated card details of user : ", company, " updated card : " , updatedCard );
        } 
        catch (AuthenticationException | InvalidRequestException | APIConnectionException | CardException | APIException e) 
        {
            LogMgr.log(LOG, LogLevel.PROCESSING1, e, "Error while updating card details of user");
        }
    }
}