/**
 * Base.Wizard 1.0
 *
 * Requiere
 *     Base 1.0
 */
$(function() {
    $.extend(Base, {
        Wizard : {

            create: function (idWizard, form, options) {

                var _i18n = {
                };

                if(options == undefined){
                    options = {}
                }

                _i18n = $.extend(true, _i18n, Base.i18n.wizard);

                if (options._i18n !== undefined && options._i18n != null) {
                    _i18n = $.extend(true, _i18n, options._i18n);
                }

                //Extract Validator Options
                var validatorOpt = options.validator;
                delete options['validator'];

                var defaultOptions = {
                    startIndex: 0,
                    animation: false,
                    animationSpeed: '0.3s',
                    customPrevious: null,
                    customNext : null,
                    customSubmit : null
                };

                var finallyOptions = $.extend(true, defaultOptions, options);

                //Prepare Wizard KtStepper
                var stepper = document.querySelector(idWizard);

                var cantSteps = KTUtil.findAll(stepper, '[data-kt-stepper-element="nav"]').length;
                stepper.setAttribute("cantSteps", cantSteps);

                var formSubmitButton = stepper.querySelector('[data-kt-stepper-action="submit"]');
                var formContinueButton = stepper.querySelector('[data-kt-stepper-action="next"]');
                var formPreviousButton = stepper.querySelector('[data-kt-stepper-action="previous"]');

                //Create Wizard KtStepper
                var wizard = new KTStepper(stepper, finallyOptions);

                //Create Validator Form
                //Validator with Submit Handler
                var validatorDefaultOption = {
                    submitHandler: function(form, validator, submitButton){
                         // Validate form before submit
                         if (validator) {
                            validator.validate().then(function (status) {

                                submitButton.disabled = true;

                                if (status == 'Valid') {
                                    submitButton.setAttribute('data-kt-indicator', 'on');

                                    // Disable button to avoid multiple click
                                    submitButton.disabled = true;

                                    //Custom Submit
                                    if(finallyOptions.customSubmit != undefined && finallyOptions.customSubmit != null && $.isFunction(finallyOptions.customSubmit)) {
                                        finallyOptions.customSubmit(wizardPlugin, form, validator, submitButton);
                                    }
                                    else{
                                        form.submit();
                                    }
                                } else {
                                    // Show error message.
                                    submitButton.removeAttribute('data-kt-indicator');
                                    submitButton.disabled = false;

                                    Base.Alert.custom({
                                        text: "Errores detectados, por favor corríjalos para finalizar.",
                                        icon: "error",
                                        buttonsStyling: false,
                                        confirmButtonText: "Aceptar",
                                        customClass: {
                                            confirmButton: "btn btn-primary"
                                        }
                                    });
                                }
                            });
                        }
                    },
                    submitButton: formSubmitButton
                }
                var validatorOpt = $.extend(true, validatorDefaultOption, validatorOpt);
                var validator = form.QxForm().validate(validatorOpt);

                //Validator Add Wizard Plugin if not Register
                validator.registerPlugin("wizard",
                    new FormValidation.plugins.Wizard({
                        stepSelector: '.base-wizard-step',
                        nextButton: idWizard + '-fvw-next',
                        prevButton: idWizard + '-fvw-previous',
                        onStepValid: function(e){
                        },
                        onStepInvalid: function(e) {
                            Base.Alert.custom({
                                text: "Errores detectados, por favor corríjalos para continuar.",
                                icon: "error",
                                buttonsStyling: false,
                                confirmButtonText: "Aceptar",
                                customClass: {
                                    confirmButton: "btn btn-primary"
                                },
                                callBackThen: function(result){
                                    KTUtil.scrollTop();
                                }
                            });
                        },
                        onStepActive: function(e) {
                            wizard.goTo(e.step+1);
                            KTUtil.scrollTop();
                        }
                    })
                );
                var wizardPlugin = validator.getPlugin('wizard');


                //Events for Wizard KtStepper
                // Stepper change event
                wizard.on('kt.stepper.changed', function (stepper) {

                    if (wizard.getCurrentStepIndex() === cantSteps) {
                        formSubmitButton.classList.remove('d-none');
                        formSubmitButton.classList.add('d-inline-block');
                        formContinueButton.classList.add('d-none');
                    } else {
                        formSubmitButton.classList.remove('d-inline-block');
                        formSubmitButton.classList.remove('d-none');
                        formContinueButton.classList.remove('d-none');
                    }
                });

                //Next Event. WizardPlugin: .goToPrevStep(), .goToNextStep()
                wizard.on('kt.stepper.next', function (stepperElement) {
                    var stepIndex = $(idWizard).QxWizard().currentStep();
                    console.log("Wizard Next: " + stepIndex);

                    if(finallyOptions.customNext != undefined && finallyOptions.customNext != null && $.isFunction(finallyOptions.customNext)) {
                        finallyOptions.customNext(wizardPlugin, stepIndex, form, validator);
                    }
                    else{
                        wizardPlugin.goToNextStep();
                    }
                });


                //Prev Event
                wizard.on('kt.stepper.previous', function (stepperElement) {
                    var stepIndex = $(idWizard).QxWizard().currentStep();
                    console.log("Wizard Previous: " + stepIndex);

                    if(finallyOptions.customPrevious != undefined && finallyOptions.customPrevious != null && $.isFunction(finallyOptions.customPrevious)) {
                        finallyOptions.customPrevious(wizardPlugin, stepIndex, form, validator);
                    }
                    else{
                        wizardPlugin.goToPrevStep();
                    }
                });

                return wizard;
            },

            _qxWizard : function (wizard) {

                return {

                    ver : function () {

                        console.log("Base.Wizard 1.0");
                        console.log("Requiere: Base 1.0;");
                    },

                    instance : KTStepper.getInstance(wizard[0]),

                    cantSteps: function(){

                        return parseInt(wizard[0].getAttribute('cantSteps'));
                    },

                    currentStep: function(){

                        return this.instance.getCurrentStepIndex();
                    },

                    getStepDirection : function() {

                        let index = this.instance.getPassedStepIndex();
                        let current = this.instance.getCurrentStepIndex();

                        if ( index < current ) {
                            return 'next';
                        } else {
                            return 'previous';
                        }
                    }
                }
            }
        }
    });

    $.fn.QxWizard = function () {

        var wizard = this;

        return Base.Wizard._qxWizard(wizard);
    }
}); 