/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'jquery',
    'ko',
    'uiComponent',
    'WriteTextAI_WriteTextAI/js/model/total-credits',
    'WriteTextAI_WriteTextAI/js/model/grid/transfer-prompt',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'WriteTextAI_WriteTextAI/js/model/grid/transfer'
], function ($, ko, Component, totalCredits, transferPrompt, referenceProducts, transfer) {
    'use strict';

    /**
     * @var {Component} self
     */
    var self;

    return Component.extend({
        defaults: {
            fieldsSelector: '#wtaiBulkTransferForm input[name="fields[]"]',
            checkboxSelector: '#wtaiBulkTransferForm .wtai-transfer-prompt input',
            storeId: 0,
            isCronRunning: false,
            selectAllPromptFields: null,
            selectedFields: [],
            selectedStores: []
        },

        /** @inheritdoc */
        initialize: function () {
            this._super();

            $('#wtaiBulkTransferForm > *').applyBindings(this);

            self = this;

            self.updateSelect();
            self.initPreferences();
            transfer.isCronRunning(self.isCronRunning);

            self.selectedFields.subscribe(function (selectedFields) {
                self.updateSelect();
                self.savePreferences('transfer', selectedFields);
                transferPrompt.selectedFields(selectedFields);
            });

            self.selectAllPromptFields.subscribe(function (selectAllPromptFields) {
                transferPrompt.selectAllPromptFields(selectAllPromptFields);
            });

            self.selectedStores.subscribe(function (selectedStores) {
                transferPrompt.selectedStores(selectedStores);
            });

            transferPrompt.storeFilter.subscribe(function (storeId) {
                self.selectedStores([storeId.toString()]);
            });
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'storeId',
                    'selectedFields',
                    'selectAllPromptFields',
                    'selectedStores'
                ]);

            return this;
        },

        /**
         * Save user preferences
         *
         * @param {string} field
         * @param {array} selected
         *
         * @returns {void}
         */
        savePreferences: function (field, selected) {
            var value = selected;
            
            if (value.length <= 0) {
                value = '';
            }

            $.ajax({
                url: self.saveUrl,
                type: 'POST',
                data: {
                    [field]: value,
                    entity_type: 'product',
                    scope: 'grid'
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            });
        },

        /**
         * Initialize preferences
         *
         * Set model values on page load.
         * Model values updates on change.
         * Retain selected fields when reopening the modal.
         */
        initPreferences: function () {
            var storeId = transferPrompt.storeFilter();

            if (!transferPrompt.initialized()) {
                transferPrompt.selectedFields(self.selectedFields());
                transferPrompt.selectAllPromptFields(self.selectAllPromptFields());
                self.selectedStores([storeId.toString()]);
                transferPrompt.selectedStores([storeId.toString()]);
                transferPrompt.initialized(true);
            } else {
                self.selectedFields(transferPrompt.selectedFields());
                self.selectAllPromptFields(transferPrompt.selectAllPromptFields());
                self.selectedStores(transferPrompt.selectedStores());
            }
        },

        /**
         * Check if the store checkbox is disabled
         *
         * @param {string} value
         * @returns {boolean}
         */
        isDisabled: function (value) {
            return parseInt(this.storeId()) === parseInt(value);
        },

        /**
         * Detect select all checkbox changes
         */
        selectAllPromptFieldsChanged: function () {
            var checked = self.selectAllPromptFields(),
                allFields = $(self.fieldsSelector)
                    .not('[value=\'all\']')
                    .map(function () {
                        return $(this).val();
                    })
                    .get();

            self.selectedFields(checked ? allFields : []);
        },

        /**
         * Update all checkboxes
         */
        updateSelect: function () {
            var selector = $(self.fieldsSelector).not('[value=\'all\']'),
                selected = 0;

            selector.each(function () {
                if ($(this).is(':checked')) {
                    selected++;
                }
            });

            if (selected === selector.length) {
                self.selectAllPromptFields(true);
            } else {
                self.selectAllPromptFields(false);
            }
        }
    });
});
