import pagSeguroService from "@/services/resources/PagSeguroService";

export default {


    initPagSeguro: context => {

        let pagseguro = document.createElement("script");
        pagseguro.setAttribute(
            "src",
            "https://stc.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js"
        );
        document.head.appendChild(pagseguro);
        var vm = this;
        setTimeout(() => {
            context.dispatch('setPagSeguroSession');
        }, 2000);


    },
    setPagSeguroSession: context => {
        var service = pagSeguroService.build();
        var directPayment = PagSeguroDirectPayment;


        return new Promise((resolve, reject) => {
            service
                .read({ id: "/session" })
                .then(resp => {

                    directPayment.setSessionId(resp.id);
                    context.commit('setSessionId', resp.id);
                    context.dispatch('setSenderHash');
                    resolve(resp);
                })
                .catch(err => {
                    console.log(err);

                    reject(err);
                })

        });


    },
    setSenderHash: context => {

        PagSeguroDirectPayment.onSenderHashReady(function (response) {
            if (response.status == 'error') {
                console.log(response.message);
                alert("Falha na ação setSenderHash");
                return false;
            }
            context.commit('setSenderHash', response.senderHash);
        });

    },
    setBrand: (context, payload) => {
        var lessSpaceCardNumber = payload.replace(/[^\d.-]/g, "");
       

return new Promise( (resolve,reject) => {
   
    if (lessSpaceCardNumber.length !== 6) {
       
            resolve({});
            return;
           }

    PagSeguroDirectPayment.getBrand({
        cardBin: lessSpaceCardNumber,
        success: function (response) {
            context.commit('setBrand', response.brand.name);
            context.dispatch('getInstallments');
            resolve(response);
        },
        error: function (response) {
            context.commit('setBrand', null);
            context.commit('setInstallments', []);
            console.error(response);
           reject(response);
        },
        complete: function (response) {
            context.commit('setCreditCardToken', null);
        }
    });


} );
    },
    getInstallments: context => {

        var maxInstallmentNoInterest = (typeof(context.rootGetters.getBenchmarkingRange) == 'undefined')? 
        1 : context.rootGetters.getBenchmarkingRange.no_charge_installment_credit_card;

        
        PagSeguroDirectPayment.getInstallments({
            amount: context.rootGetters.getTotalToPay,
            maxInstallmentNoInterest: maxInstallmentNoInterest, 
            brand: context.state.brand,
            success: function (response) {
                context.commit('setInstallments', response.installments[context.state.brand]);

            },
            error: function (response) {
                console.error(response);
                context.commit('setInstallments', []);
            },
            complete: function (response) {
                // Callback para todas chamadas.
            }
        });
    },
    createCreditCardToken: (context, payload) => {


        var creditCardNumber = payload.cardNumber.replace(/[^\d.-]/g, "");
        return new Promise((resolve, reject) => {

            PagSeguroDirectPayment.createCardToken({
                cardNumber: creditCardNumber, // Número do cartão de crédito
                brand: context.state.brand, // Bandeira do cartão
                cvv: payload.cardCvv, // CVV do cartão
                expirationMonth: payload.cardMonth, // Mês da expiração do cartão
                expirationYear: payload.cardYear, // Ano da expiração do cartão, é necessário os 4 dígitos.
                success: function (response) {
                    context.commit('setCreditCardToken', response.card.token);
                    resolve(resolve);
                },
                error: function (response) {

                    reject(response);
                },
                complete: function (response) {
                    // Callback para todas chamadas.
                }
            });

        });
    },

    PayOrderWithCreditCard: (context,payload) => {


        var dataToSend = {};
        
        Object.assign(dataToSend, context.state);

        dataToSend.order_id =  context.rootState.orderCreate.orderId;
        var vm = this;
        return new Promise( (resolve, reject) => {

            var service = pagSeguroService.build();
            
            service.create(dataToSend)
            .then( (resp) => {
                resolve(resp);
            } )
            .catch( (err) => {

                reject(err);

            } );

        } );

    }
}
