define([
    'Magento_Checkout/js/view/payment/default',
    'Magento_Checkout/js/model/quote',
    'jquery',
    'ko',
    'Magento_Checkout/js/model/payment/additional-validators',
    'Magento_Checkout/js/action/set-payment-information',
    'mage/url',
    'Magento_Customer/js/model/customer',
    'Magento_Checkout/js/action/place-order',
    'Magento_Checkout/js/model/full-screen-loader',
    'Magento_Ui/js/model/messageList',
    'Magento_Checkout/js/model/shipping-save-processor',
    'Magento_Payment/js/view/payment/cc-form'

], function (Component, quote, $, ko, additionalValidators, setPaymentInformationAction, url, customer, placeOrderAction, fullScreenLoader, messageList, shippingSaveProcessor) {
    'use strict';
    var awaitSDKJSDownload = function (resolve, reject, config, count) {
        console.log("Awaiting SDK JS to be downloaded");
        if (window.loadBillDeskSdk != null) {
            resolve(config);
            return;
        }

        console.log("SDK JS is not downloaded, will wait further. Count: " + count);

        if (count > 300) {
            reject("It appears that SDK JS libraries could not be loaded in time");
            return;
        }

        setTimeout(awaitSDKJSDownload, 200, resolve, reject, config, count + 1);
    };


    return Component.extend({
        defaults: {
            template: 'Magento_Billdesk/payment/billdesk-form',
            billdeskDataFrameLoaded: false,
            billdesk_response: {}
        },
        TestConnectivity: function () {
            console.log('inside TestConnectivity function');
        },
        getMerchantId: function () {
            return window.checkoutConfig.payment.billdesk.merchant_id;
        },

       /*  getMerchantKey: function () {
            return window.checkoutConfig.payment.billdesk.merchant_key;
        }, */

        getClientId: function () {
            return window.checkoutConfig.payment.billdesk.client_id;
        },
        getJoseEncryptionKey: function () {
            return window.checkoutConfig.payment.billdesk.jose_encryption_key;
        },

        getJoseSigningKey: function () {
            return window.checkoutConfig.payment.billdesk.jose_signing_key;
        },

        getMerchantLogo: function () {
            return window.checkoutConfig.payment.billdesk.merchant_logo;
        },

        getItemCode: function () {
            return window.checkoutConfig.payment.billdesk.item_code;
        },

        getRetryCount: function () {
            return window.checkoutConfig.payment.billdesk.retry_count;
        },

        getChildWindow: function () {
            return window.checkoutConfig.payment.billdesk.child_window;
        },

        getPaymentCategory: function () {
            return window.checkoutConfig.payment.billdesk.payment_category;
        },

        getEnvVariable: function () {
            return window.checkoutConfig.payment.billdesk.env_variable;
        },

        context: function () {
            return this;
        },

        isShowLegend: function () {
            return true;
        },

        getCode: function () {
            return 'billdesk';
        },

        isActive: function () {
            return true;
        },

        isAvailable: function () {
            return this.billdeskDataFrameLoaded;
        },

        handleError: function (error) {
            if (_.isObject(error)) {
                this.messageContainer.addErrorMessage(error);
            } else {
                this.messageContainer.addErrorMessage({
                    message: error
                });
            }
        },

        InvokeSdk: async function () {
            var self = this;
            var envar = self.getEnvVariable();
            if (envar === 'UAT') {
                var head = document.getElementsByTagName('HEAD')[0];

                var script = document.createElement('script');
                script.type = "module";
                script.rel = 'modulepreload';

                script.src = 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.esm.js';
                document.head.appendChild(script);

                var script1 = document.createElement('script');
                script1.nomodule = "";
                script1.rel = 'modulepreload';
                script1.src = 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.js';
                document.head.appendChild(script1);

               // var head = document.getElementsByTagName('HEAD')[0];
                var link = document.createElement('link');
                //link.rel = 'prefetch';
                link.rel = 'preload';
                link.type = 'text/css';
                link.href = 'https://uat1.billdesk.com/merchant-uat/sdk/dist/billdesksdk/billdesksdk.css';
                document.head.appendChild(link);
               // head.appendChild(link);
            } else {
                var script = document.createElement('script');
                script.type = "module";
                script.src = 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.esm.js';
                document.head.appendChild(script);

                var script1 = document.createElement('script');
                script1.nomodule = "";
                script1.src = 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk.js';
                document.head.appendChild(script1);

                var head = document.getElementsByTagName('HEAD')[0];
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = 'https://pay.billdesk.com/jssdk/v1/dist/billdesksdk/billdesksdk.css';
                head.appendChild(link);
            }

            var config = await self.getSdkConfig();
            console.log('config: ', config);
            //this is the function of sdk library
            window.loadBillDeskSdk(config);


        },

        getSdkConfig: async function () {
            var self = this;
            var retry_count = self.getRetryCount();
            var childwindow = self.getChildWindow();
            var merchantLogo = self.getMerchantLogo();

            var txn = '';
            const flowtype = "payments";
            const responseCallback = function (response) {
                let l = url.build('billdesk/payment/OrderProcessWithoutChildWindow');
                console.log('Callback url: ', response);

                console.log('Callback response: ', response);

                if (response.status == '111') {
                    self.handleError('Error : Payment Closed.');
                } else {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = l;

                    const hiddenField = document.createElement('input');
                    hiddenField.type = 'hidden';
                    hiddenField.name = 'transaction_response';
                    console.log('Terminal state from response: ', response.txnResponse.terminal_state);
                    console.log('Transation response from response: ', response.txnResponse.transaction_response);
                    if (response.txnResponse.terminal_state == 'N') {
                        hiddenField.value = response.txnResponse.terminal_state;
                    } else {
                        hiddenField.value = response.txnResponse.transaction_response;
                    }


                    form.appendChild(hiddenField);

                    document.body.appendChild(form);

                    form.submit();
                }
            }
            await jQuery.ajax({
                type: "POST",
                url: url.build('billdesk/payment/orderCreate'),
                success: function (response) {
                    console.log('Create order response: ', response);
                    if (response.status == '401' || response.status == '500' || response.status == '422') {
                        self.handleError('Error in order Creation, Temporarly we are not able to Create Order. ' + response.message);
                    }

                    txn = response;
                },
                error: function (response) {
                    //self.handleError('Error in create order :  '+response);
                    console.error('Error in create order :  ', response);
                    if (response.status == '500') {
                        self.handleError('Error in order Creation, Temporarly we are not able to Create Order. ' + response.statusText);
                    }
                }
            });
            const flowConfig = {
                merchantId: txn.mercid,
                bdOrderId: txn.bdorderid,
                authToken: txn.links['1'].headers.authorization,
                childWindow: JSON.parse(childwindow),
                retryCount: parseInt(retry_count),
            }
            var pay_category = self.getPaymentCategory();

            if (pay_category === "" || pay_category === null) {

            } else {
                var payment_category = pay_category.split(",").map(item => item.trim());
                var pref = {
                    "payment_categories": payment_category
                }
                if (payment_category[0].length != '0') {
                    flowConfig.prefs = pref;
                }
            }

            var sdkConfig = {
                responseHandler: responseCallback,
                merchantLogo: merchantLogo,
                flowConfig: flowConfig,
                flowType: flowtype
            }

            var promise = new Promise(function (resolve, reject) {
                awaitSDKJSDownload(resolve, reject, sdkConfig, 0);
            });

            return promise;
        },
    });
});
