define([
    'jquery',
    'underscore',
    'mage/template',
    'mage/smart-keyboard-handler',
    'mage/translate',
    'priceUtils',
    'mage/url',
    'jquery-ui-modules/widget',
    'jquery/jquery.parsequery',
    'mage/validation/validation',
    'jqueryHistory'
], function ($, _, mageTemplate, keyboardHandler, $t, priceUtils, urlBuilder) {
    'use strict';

    
    return function (SwatchRenderer) {
        var ajaxcall = 0;
        var simpleproductid;
        var repalcingDataEnabled = false;
        var selectFirstForOther = false;
        $.widget('mage.SwatchRenderer', SwatchRenderer, {
            /**
             * Get chosen product
             *
             * @returns int|null
             */
            getProduct: function () {
                var result = this._super();
                if (result) {
                    ajaxcall = 1;
                    simpleproductid = result;
                    this._UpdateSimpleProductQty();
                } else {
                    ajaxcall = 0;
                }
                return result;
            },

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

            _init: function () {
                if ($(this.element).attr('data-rendered')) {
                    return;
                }
                if (!window.isMageantsScpChild) {
                    repalcingDataEnabled = true;
                }
                this._super();
                if (this.options.jsonConfig !== '' && this.options.jsonSwatchConfig !== '') {
                    this._disableEmptyFirstOption();
                    var delayTime = 1000;
                    setTimeout(function(){
                        repalcingDataEnabled = true;
                        selectFirstForOther = true;
                    }, delayTime);
                }
            },

            /**
             * Event for swatch options
             *
             * @param {Object} $this
             * @param {Object} $widget
             * @private
             */
            _OnClick: function ($this, $widget) {
                $widget.bindings;
                if ($this.hasClass('selected')) {
                    return; // Stop further execution if already selected
                }
                this._super($this, $widget);
                var products = $widget._CalcProducts();
                if (products.length && !this.options.jsonConfig.doNotReplaceData) {
                    var simpleProductId = products[0];
                    $widget._ReplaceData(simpleProductId);
                    /* Update input type hidden - fix base image doesn't change when choose option */
                    if (simpleProductId && document.getElementsByName('product').length) {
                        document.getElementsByName('product')[0].value = simpleProductId;
                    }
                }
                if (!window.isMageantsScpChild && selectFirstForOther && typeof this.options.is_PDP_page !== 'undefined' && this.options.is_PDP_page) {
                    selectFirstForOther = false;
                    this._selectFirstForAll();
                }
            },

            /**
             * Event for select
             *
             * @param {Object} $this
             * @param {Object} $widget
             * @private
             */
            _OnChange: function ($this, $widget) {
                this._super($this, $widget);
                var products = $widget._CalcProducts();
                if (products.length && !this.options.jsonConfig.doNotReplaceData) {
                    var simpleProductId = products[0];
                    $widget._ReplaceData(simpleProductId);
                    /* Update input type hidden - fix base image doesn't change when choose option */
                    if (simpleProductId && document.getElementsByName('product').length) {
                        document.getElementsByName('product')[0].value = simpleProductId;
                    }
                }
                if (!window.isMageantsScpChild && selectFirstForOther && typeof this.options.is_PDP_page !== 'undefined' && this.options.is_PDP_page) {
                    selectFirstForOther = false;
                    this._selectFirstForAll();
                }
            },

            /**
             * 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;
                }
                return this._super();
            },

            _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);
                        }
                    });
                }
                this._disableEmptyFirstOption();
            },

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

            _selectFirstForAll: function () {
                var swatOpt = this.element.find('.swatch-attribute .swatch-attribute-options');
                $(swatOpt).each(function() {
                    if ($(this).find('.swatch-option.selected').length === 0) {
                        $(this).find('.swatch-option').not('.disabled').first().click();
                    }
                });
                this.element.find('.swatch-attribute-options select.swatch-select').each(function () {
                    var $select = $(this);
                    if (!$select.val() || $select.val() === '' || $select.val() === 0) {
                        var firstValidOption = $select.find('option[value!=""]').not('[value="0"]').not('.disabled').first();
                        if (firstValidOption.length) {
                            $select.val(firstValidOption.val()).trigger('change');
                        }
                    }
                });
            }
        });
        return $.mage.SwatchRenderer;
    };
});
