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 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
    {
        LogMgr.log(LOG, LogLevel.PROCESSING1,"In UpdateCardFP : " );

        Stripe.apiKey = StripeUtils.STRIPE_KEY;
            
        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);
            
            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));
            }
            
            updateParams.put("name", name);
            updateParams.put("address_zip", addressZip);
            
            card.update(updateParams);
            
            company.setNameOnCard(name);
            company.setCardPostCode(addressZip);
            
        } 
        catch (AuthenticationException | InvalidRequestException | APIConnectionException | CardException | APIException e) 
        {
            LogMgr.log(LOG, LogLevel.PROCESSING1, e, "Error while making payment");
        }

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