
$(function () {
    ini();
});


export const getQRCode = (date) =>{
    return dateFormat(date,"DD-MM-YYYY HH:mm:ss")
};


function ini(){

   const locale = sessionStorage.getItem('locale');
   if(locale){
       payment.init({
           locale : locale
       });
   }
   $('#btnBackLable').text(payment.texts.btnBack);

   //mobilepayment
   const walletSession = sessionStorage.getItem('walletPayment');
   const walletPayment = $.parseJSON(walletSession);
   const transactionid = walletPayment.transactionid;
   const webtoken = walletPayment.webtoken;
   const totalamount = walletPayment.totalamount;
   payment.showLog('transactionid:' +  transactionid + ', webtoken:' + webtoken + ', totalamount:' + totalamount);

   const walletRspSession = sessionStorage.getItem('walletRsp');
   const walletRsp = $.parseJSON(walletRspSession);
   const fpsQRCodeImgBase64 = walletRsp.fpsqrcodeimgbase64;
   const fpsMerchantTimeoutDateTime = walletRsp.fpsmerchanttimeoutdatetime;
   const openPASGUrl = payment.config.pasgPath + '?pay_req_obj=' + encodeURIComponent(walletRsp.fpsqrcodeurl) + '&callback='
       + encodeURIComponent(payment.config.domain + payment.config.fpscallbackPagePath);

   $('#totalAmt').text(totalamount);
   $('#fps').text(payment.texts.fps);
   $('#continueToPay').text(payment.texts.continueToPay);
   $('#paymentDetailsTitle').text(payment.texts.paymentDetailsTitle);
   $('#paymentAmount').text(payment.texts.paymentAmount);
   $('#scanQRCode').text(payment.texts.scanQRCode);

   let obj = $('#qrCodeValidTime').text(payment.texts.qrCodeValidTime);
   obj.html(obj.html().replace(/\n/g,'<br/>'));

   const paymentStatusApi = async () => {
       const paymentStatusResp = await payment.paymentEnquiry(transactionid, webtoken);
       return paymentStatusResp;
   }
   const validatePaymentStatus = paymentStatusResp => {
       if (paymentStatusResp.paymentdetail.result.paymentstatuscode !== 'INPR') {
           return true;
       }
       return false;
   }

   renderFpsQRCodeTemplate(fpsQRCodeImgBase64, $('#fpsQRCodeTemplate').html());
   payment.showLog('fpsQRCodeImgBase64:' +  fpsQRCodeImgBase64);
   payment.showLog('fpsPollInterval:' +  payment.config.fpsPollInterval);
   payment.showLog('fpsMerchantTimeoutDateTime:' +  fpsMerchantTimeoutDateTime);

   if (/Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent)) {
       payment.showLog('Mobile web browser');
       renderOpenFPSPaymentAppTemplate(openPASGUrl, $('#openFPSPaymentAppTemplate').html());
   } else {
       payment.showLog('Desktop web browser');
   }

   poll({
       fn: paymentStatusApi,
       validate: validatePaymentStatus,
       interval: payment.config.fpsPollInterval,
       timeout: fpsMerchantTimeoutDateTime
   }).then(resp => {
       sessionStorage.setItem('walletRsp', JSON.stringify(resp));

       const paymentstatuscode = resp.paymentdetail.result.paymentstatuscode;
       payment.showLog('pollForPaymentStatus:' +  paymentstatuscode);

       if (paymentstatuscode === 'APPR') {
           const timestamp = '?t=' + Date.now();
           window.top.location.href = payment.config.domain + payment.config.ackPagePath + timestamp;
       } else if (paymentstatuscode === 'CANC') {
           window.top.location.href = payment.config.domain + payment.config.indexPagePath;
       } else {
           window.top.location.href = payment.config.domain + payment.config.errPagePath;
       }
   }).catch(err => {
       payment.showLog('pollForPaymentStatus error: ' + err);
       cancelFPSPayment();
       window.top.location.href = payment.config.domain + payment.config.errPagePath;
   });

}

function renderFpsQRCodeTemplate(fpsQRCodeImgBase64, template) {
   // payment.showLog('template:' +  template);
   Mustache.parse(template);
   const rendered = Mustache.render(template, {fpsQRCodeImgBase64: fpsQRCodeImgBase64});
   $('#fpsQRCodePanel').html(rendered);
   // $('#fpsQRCodePanel').removeClass('hidden');
}

function renderOpenFPSPaymentAppTemplate(openPASGUrl, template) {
   payment.showLog('renderOpenFPSPaymentAppTemplate template:' +  template);
   payment.showLog('renderOpenFPSPaymentAppTemplate openPASGUrl:' +  openPASGUrl);
   Mustache.parse(template);
   const rendered = Mustache.render(template, {openPASGUrl: openPASGUrl});
   payment.showLog('renderOpenFPSPaymentAppTemplate rendered:' +  rendered);
   $('#openFPSPaymentAppContent').html(rendered);
   // $('#openFPSPaymentApp').removeClass('hidden');
}

function cancelFPSPayment() {
   const walletSession = sessionStorage.getItem('walletPayment');
   const walletPayment = $.parseJSON(walletSession);
   const walletRspSession = sessionStorage.getItem('walletRsp');
   const walletRsp = $.parseJSON(walletRspSession);
   const reqJson = {
       'transactionid':walletPayment.transactionid,
       'webtoken':walletPayment.webtoken,
       'paymentid': walletRsp.paymentid,
   }
   payment.cancelPayment(reqJson);
}

function cancelBtnOnClick(event) {
   event.onclick=null;
   $('#cancelBtnIcon').remove();
   $('#cancelBtn').removeClass("btn-danger").addClass("btn-secondary disabled");
   $('#cancelBtnText').html('Cancelling ... ');

}
