/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpPaypal
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
/*browser:true*/
/*global define*/
define(
    [
        'ko',
        'jquery',
        'Magento_Checkout/js/view/payment/default',
        'Magento_Checkout/js/action/set-payment-information',
        'Magento_Checkout/js/action/select-payment-method',
        'Magento_Checkout/js/checkout-data',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/model/totals',
        'mage/translate',
        'Magento_Checkout/js/action/redirect-on-success'        
    ],
    function (
        ko,
        $,
        Component,
        setPaymentInformationAction,
        selectPaymentMethodAction,
        checkoutData,
        quote,
        totals,
        $t,
        redirectOnSuccessAction
    ) {
        'use strict';
        /**
         * braintreeConfig contains all the payment configuration
         */
         var braintreeConfig = window.checkoutConfig.payment.mppaypal;
         /**
          * customerEmail customer email
          */
         var customerEmail = window.customerData.email;
         var customerCountry = window.customerData.defaultCountryId;

        return Component.extend(
            {
                defaults: {
                    template: 'Webkul_MpPaypal/payment/mppaypal',
                    config: window.checkoutConfig.payment.mppaypal
                },

                initialize: function() {
                    var that = this;
                    that._super();
                    
                },
                
                /**
                 * @override
                 */
                initObservable: function () {
                    this._super()
                        .observe(
                            [
                                'intent',
                                'orderID',
                                'payerID',
                                'paymentToken',
                                'sellerEmail',
                                'quoteID'
                            ]
                        );
                    return this;
                },

                bindPayPalBtn: function() {
                    var that = this;
                    const request = {
                        post: function (url, data) {
                            return new Promise(function (resolve) {
                                let http = new XMLHttpRequest();
                                http.open("POST", url, true);
                                http.setRequestHeader("Content-type", "application/json");
                                http.onreadystatechange = function() {
                                    if (this.readyState === 4 && this.status === 200) {
                                        return resolve(JSON.parse(this.responseText));
                                    }
                                };
                                http.send(JSON.stringify(data));
                            });
                        }
                    };
                    var sellerEmail = '';
                    var quoteID = '';
                    paypal.Button.render({

                        // Set your environment
                        env: that.config.environment,
                
                        // Set style of buttons
                        style: {
                            layout: 'horizontal',   // horizontal | vertical
                            size:   'medium',   // medium | large | responsive
                            shape:  'pill',         // pill | rect
                            color:  'gold',         // gold | blue | silver | black,
                            fundingicons: false,    // true | false,
                            tagline: false,          // true | false,
                        },
                
                        // Set allowed funding sources
                        funding: {
                            allowed: [
                                paypal.FUNDING.CARD
                            ],
                            disallowed: [ ]
                        },
                
                        // Show the buyer a 'Pay Now' button in the checkout flow
                        commit: false,
                
                        // payment() is called to start the payment flow when a button is clicked
                        payment: function() {
                            const postData = {
                                'update': null,
                                'flow': 'shortcut',
                                'form_key':$.mage.cookies.get('form_key')
                            };
                            return request.post(
                                that.config.createOrderUrl,
                                postData
                            ).then(function(returnObject) {
                                var returnData = JSON.parse(returnObject);
                                sellerEmail = returnData['email_address'];
                                quoteID = returnData['quote_id'];
                                return returnData.id;
                            });
                        },
                
                        // onAuthorize() is called when the buyer approves the payment
                        onAuthorize: function(data) {
                            that.intent(data.intent);
                            that.orderID(data.orderID);
                            that.payerID(data.payerID);
                            that.paymentToken(data.paymentToken);
                            that.sellerEmail(sellerEmail);
                            that.quoteID(quoteID);
                            that.placeOrder();
                        },
                
                        // onCancel() is called when the buyer cancels payment authorization
                        onCancel: function(data) {
                            console.log(data)
                        },
                
                        // onError() is called when there is an error in this Checkout.js script
                        onError: function (error) {
                            console.log(error)
                        }
                
                    }, '#paypalCheckoutContainer');
                },
              
                /**
                 * validate  to validate the payment method fields at checkout page
                 *
                 * @return boolean
                 */
                validate: function () {
                    return true;
                },

                /**
                 * selectPaymentMethod called when payment method is selected
                 * 
                 * @return boolean
                 */
                selectPaymentMethod: function () {
                    selectPaymentMethodAction(this.getData());
                    checkoutData.setSelectedPaymentMethod('mppaypal');                    
                    return true;                 
                },

                /**
                 * totals set order totals from quote
                 */
                totals: quote.getTotals(),
              
                /**
                 * getGrandTotal get order grand total
                 *
                 * @return decimal
                 */
                getGrandTotal:function () {
                    var price = 0;
                    if (this.totals()) {
                        price = totals.getSegment('grand_total').value;
                    }
                    return price;
                },

                /**
                 * getData set payment method data for making it available in PaymentMethod Class
                 *
                 * @return object
                 */
                getData: function () {
                    var self = this;
                    return {
                        'method': 'mppaypal',
                        'additional_data': {
                            'intent' : self.intent(),
                            'orderID' : self.orderID(),
                            'payerID' : self.payerID(),
                            'paymentToken' : self.paymentToken(),
                            'sellerEmail' : self.sellerEmail(),
                            'quoteID' : self.quoteID(),
                        },
                    };
                }
            }
        );
    }
);
