package performa.form;

import com.stripe.Stripe;
import com.stripe.model.Card;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.appservices.config.ConfigMgr;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.logging.LoggingArea;
import oneit.objstore.StorageException;
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.StringUtils;
import oneit.utils.parsers.FieldException;
import performa.orm.HiringTeam;
import performa.utils.StripeUtils;


public class ReplaceCardFP extends SaveFP
{

    public  static final String         STRIPE_KEY      =   ConfigMgr.getKeyfileString("stripe.key","");
    public  static final String         STRIPE_PUB_KEY  =   ConfigMgr.getKeyfileString("stripe.pubkey","");
    private static final LoggingArea    LOG             =   LoggingArea.createLoggingArea("ReplaceCardFP");

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map p) throws BusinessException, StorageException
    {
        LogMgr.log(LOG, LogLevel.PROCESSING1,"In ReplaceCardFP to replace card details");

        replaceCardDetails(process, submission);

        return super.processForm(process, submission, p);
    }
    
    
    public static void replaceCardDetails(ORMProcessState process, SubmissionDetails submission) throws BusinessException
    {
        HttpServletRequest  request =   submission.getRequest();
        
        Stripe.apiKey = STRIPE_KEY;
            
        String  token   = request.getParameter("stripe-token-id");
        
        if(StringUtils.subBlanks(token) == null)
        {
            throw new BusinessException("Updating card details failed, Please contact adminstrator for more info.");
        }
        
        try
        {
            HiringTeam  hiringTeam  =   (HiringTeam)process.getAttribute("HiringTeam");
            Card        card        =   StripeUtils.updateCardDetails(hiringTeam, token);
            
            LogMgr.log(LOG, LogLevel.PROCESSING1,"In ReplaceCardFP replacing card details of hiringTeam: ", hiringTeam, " card : " , card );
            
            if (card != null)
            {
                hiringTeam.setNameOnCard(card.getName());
                hiringTeam.setCardPostCode(card.getAddressZip());
                hiringTeam.setCardID(card.getId());
                
                LogMgr.log(LOG, LogLevel.PROCESSING1,"In ReplaceCardFP card details updated of hiring team: ", hiringTeam);
            }
        }
        catch(StorageException | FieldException e)
        {
            LogMgr.log(LOG, LogLevel.PROCESSING1, e, "Error while replacing stripe card details");
        }
    }
}