/**
 * @category Mageants SimpleConfigurable
 * @package Mageants_SimpleConfigurable
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */
define([
    'jquery',
    'underscore',
    'mage/template',
    'mage/translate',
    'priceUtils',
    'mage/url',
    'priceBox',
    'jquery-ui-modules/widget',
    'jquery/jquery.parsequery',
    'fotoramaVideoEvents',
    'jqueryHistory'
], function ($, _, mageTemplate, $t, priceUtils, urlBuilder) {
    'use strict';

    return function (ConfigurableWidget) {
        var repalcingDataEnabled = false;
        var selectFirstForOther = false;
        $.widget('mage.configurable', ConfigurableWidget, {
            _create: function () {
                this._super();
                this.preSelectOptionsByAttributeMap(this._getSelectedAttributes());
            },

            /**
             * Configure an option, initializing it's state and enabling related options, which
             * populates the related option's selection and resets child option selections.
             * @private
             * @param {*} element - The element associated with a configurable option.
             */
            _configureElement: function (element) {
                this.simpleProduct = this._getSimpleProductId(element);
                this._ReplaceData(this.simpleProduct);
    
                if (this.simpleProduct && document.getElementsByName('product').length) {
                    document.getElementsByName('product')[0].value = this.simpleProduct;
                }
                var productLength = document.getElementsByName('product').length;
                if (productLength >= 1) {
                    this._UpdateSimpleProductQty();
                }
                if (!window.isMageantsScpChild) {
                    repalcingDataEnabled = true;
                }
                this._super(element);
                this._disableEmptyFirstOption();
                if (selectFirstForOther) {
                    this.element.find('select.super-attribute-select[name^="super_attribute"]').each(function () {
                        var $select = $(this);
                        if (!$select.val() || $select.val() === '') {
                            var firstValidOption = $select.find('option[value!=""]').first();
                            if (firstValidOption.length) {
                                $select.val(firstValidOption.val()).trigger('change');
                            }
                        }
                    });
                }
                var delayTime = 1000;
                setTimeout(function(){
                    repalcingDataEnabled = true;
                    selectFirstForOther = true;
                }, delayTime);
            },

            /**
             * Public method: Select configurable options based on attribute map
             * Example input: { "ram": "215", "storage": "212" }
             */
            preSelectOptionsByAttributeMap: function (optionsMap) {
                var self = this;

                Object.keys(optionsMap).forEach(function (attributeCode) {
                    var optionId = optionsMap[attributeCode];
                    attributeCode = attributeCode.replace(/^id_/, '');

                        var select = self.element.find('[data-selector="super_attribute[' + attributeCode + ']"]');

                        if (select.length && select.val() == null) {
                            select.val(optionId).trigger('change');
                        }
                });
            },

            /**
             * Get default options values settings with either URL query parameters
             * @private
             */
            _getSelectedAttributes: function () {
                if (typeof window.mageantsScpCurrentChild !== 'undefined') {
                    return window.mageantsScpCurrentChild;
                }
                if (typeof this.options.preSelectedOption !== 'undefined') {
                    return this.options.preSelectedOption;
                }
            },

            _UpdateSimpleProductQty: function () {
                if (this.simpleProduct) {
                    $.ajax({
                        type: "POST",
                        url: urlBuilder.build('simpleconfigurable/index/ajaxrequest'),
                        data : 'id='+ this.simpleProduct,
                        dataType: "json",
                        success: function(data){
                            if(data.status == "success"){
                                 $('.show_qty').html(data.success_message);
                            }else{
                                $('.show_qty').html();
                            }
                        }
                    });
                }
    
            },

            _ReplaceData: function (simpleProductId) {
                if (!repalcingDataEnabled) {
                    return;
                }
                if (typeof this.options.is_PDP_page !== 'undefined' && this.options.is_PDP_page) {
                    $.ajax({
                        url: urlBuilder.build('simpleconfigurable/index/getchildproductdata'),
                        type: 'GET',
                        dataType: 'json',
                        data: {
                            product_id: simpleProductId
                        },
                        showLoader: true,
                        success: function(response) {
                            if (response.success) {
                                $.each(response.data, function(key, item) {
                                    if ($(item.selector).length) {
                                        if(item.selector.includes('meta')){
                                            $(item.selector).attr('content', item.value);
                                        }
                                        if(item.selector.includes('canonical')){
                                            $(item.selector).attr('href', item.value);
                                        } else {
                                            $(item.selector).html(item.value);
                                        }
                                    }
                                });
    
                                if (typeof response.product_url !== 'undefined' && response.product_url) {
                                    var queryString = window.location.search;
                                    var title = $('.product-info-main .page-title-wrapper [itemprop="name"]').text();
                                    if (typeof response.data.name !== 'undefined') {
                                        title = response.data.name.value;
                                    }
                                    if (queryString) {
                                        History.replaceState(null, title, response.product_url + queryString);
                                    } else {
                                        History.replaceState(null, title, response.product_url);
                                    }
                                }
                            } else {
                                console.log('Error:', response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log('AJAX error:', error);
                        }
                    });
                }
            },

            /**
             * Function to disable the first option in select elements with
             * class "super-attribute-select" and name containing "super_attribute"
             */
            _disableEmptyFirstOption: function () {
                this.element.find('select.super-attribute-select[name^="super_attribute"]').each(function () {
                    var firstOption = $(this).find('option').first();
                    if (firstOption.val() === '') {
                        firstOption.prop('disabled', true);
                    }
                });
            }
        });
        return $.mage.configurable;
    };
});
