<?php
/**
 * Copyright © 2016 maijindou.com All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/* @var $block \Magento\ConfigurableProduct\Block\Product\Configurable\AttributeSelector */
?>
<script>
(function(){
    'use strict';
    
    var $form;

    require([
        'jquery',
        'jquery/ui',
        'Magento_Ui/js/modal/modal'
    ], function($){
        $form = $('[data-role=affected-attribute-set-selector]');
        var resetValidation = function() {
                $form.find('.messages .message.error').hide();
                $form.find('form').validation().data('validator').resetForm();
            },
            setAttributeSetId = function (id) {
                $('[data-role=new-variations-attribute-set-id]').val(id);
            },
            closeDialogAndProcessForm = function (form) {
                form.modal('closeModal').data('target').click();
            },
            newAttributeSetContainer = $('[data-role=affected-attribute-set-new-name-container]'),
            existingAttributeSetContainer = $('[data-role=affected-attribute-set-existing-name-container]');

        $form.find('input[type=text]').on('keypress',function(e){
            if(e.keyCode === 13){
                e.preventDefault();
                $form.closest('[data-role=modal]').find('button[data-action=confirm]').click();
            }
        });

        $('[data-form=edit-product]').append($('<input>', {
            type: 'hidden',
            name: 'new-variations-attribute-set-id',
            'data-role': 'new-variations-attribute-set-id'
        }));

        $form
            .modal({
                title: '<?php /* @escapeNotVerified */ echo __('Choose Affected Attribute Set'); ?>',
                closed: function () {
                    resetValidation();
                },
                buttons: [{
                    text: '<?php /* @escapeNotVerified */ echo __('Confirm'); ?>',
                    attr: {
                        'data-action': 'confirm'
                    },
                    'class': 'action-secondary',
                    click: function() {
                        var affectedAttributeSetId = $form.find('input[name=affected-attribute-set]:checked').val();
                        if (affectedAttributeSetId == 'current') {
                            setAttributeSetId($('#attribute_set_id').val());
                            closeDialogAndProcessForm($form);
                            return;
                        } else if (affectedAttributeSetId == 'existing') {
                            setAttributeSetId($('select', existingAttributeSetContainer).val());
                            closeDialogAndProcessForm($form);
                        }

                        $form.find('.messages .message.error').hide();
                        if (!$form.find('form').validation().valid()) {
                            $form.find('input[name=new-attribute-set-name]').focus();
                            return false;
                        }

                        $.ajax({
                            type: 'POST',
                            url: '<?php /* @escapeNotVerified */ echo $block->getAttributeSetCreationUrl()?>',
                            data: {
                                gotoEdit: 1,
                                attribute_set_name: $form.find('input[name=new-attribute-set-name]').val(),
                                skeleton_set: $('#attribute_set_id').val(),
                                form_key: '<?php /* @escapeNotVerified */ echo $block->getFormKey()?>',
                                return_session_messages_only: 1
                            },
                            dataType: 'json',
                            showLoader: true,
                            context: $form
                        })
                            .success(function (data) {
                                if (!data.error) {
                                    setAttributeSetId(data.id);
                                    closeDialogAndProcessForm($form);
                                } else {
                                    $form.find('.messages .message.error').replaceWith($(data.messages).find('.message.error'));
                                }
                            });

                        return false;
                    }
                },{
                    text: '<?php /* @escapeNotVerified */ echo __('Cancel'); ?>',
                    id: '<?php /* @escapeNotVerified */ echo $block->getJsId('close-button') ?>',
                    'class': 'action-close',
                    click: function() {
                        $form.modal('closeModal');
                    }
                }]
            })
            .find('input[name=affected-attribute-set]').on('change', function() {
                var affectedAttributeSet = $(this).val();
                newAttributeSetContainer[affectedAttributeSet == 'new' ? 'show' : 'hide']();
                existingAttributeSetContainer[affectedAttributeSet == 'existing' ? 'show' : 'hide']();
                resetValidation();
                if (affectedAttributeSet == 'new') {
                    newAttributeSetContainer.find('input[name=new-attribute-set-name]').focus();
                }
            });
    });
    
    require([
        'jquery'
    ], function ($) {

        /**
         * Retrieve list of attributes
         *
         * @return {Array}
         */
        var getAttributes = function ($node) {
            return $.map(
                $node.find('[data-role=configurable-attributes-container] [data-role=attribute-info]') || [],
                function (attribute) {
                    var $attribute = $(attribute);

                    return {
                        id: $attribute.find('[name$="[attribute_id]"]').val(),
                        code: $attribute.find('[name$="[code]"]').val(),
                        label: $attribute.find('[name$="[label]"]').val(),
                        position: $attribute.find('[name$="[position]"]').val()
                    };
                }
            );
        };

        /**
         * This fix was made in order to properly handle 'stopImmediatePropagation'.
         */
        $('#save-split-button .item').on('click', function(event) {
            if ($('[data-role=new-variations-attribute-set-id]').val() != '') {
                return; // affected attribute set was already chosen
            }

            var extendingAttributes = [];

            $.each(getAttributes($('[data-role=product-variations-matrix]')), function () {
                if (!$('#attribute-' + this.code + '-container').length) {
                    extendingAttributes.push(this.id);
                }
            });
            if (!extendingAttributes.length) {
                $('[data-role=new-variations-attribute-set-id]').val($('#attribute_set_id').val());
                return; // all selected configurable attributes belong to current attribute set
            }
            if (!$('[data-role=product-variations-matrix] [data-column=entity_id]')
                .closest('tr').has('input[name$="[name]"]').length
            ) {
                return; // no new simple products to save from matrix: uniting attribute set is not needed
            }

            event.stopImmediatePropagation();

            $form.data('target', event.target).modal('openModal');
        });

    });

})();
</script>
