/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/)
 * @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,
            entityType: 'category',
            selectAllPromptFields: null,
            selectedStores: []
        },

        lastSelectedStores: [],

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

            const el = document.querySelector('#wtaiBulkTransferForm');
            if (el) {
                $('#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) {
                var normalizedStores = self.normalizeSelectedStores(selectedStores);

                if (JSON.stringify(normalizedStores) !== JSON.stringify(selectedStores)) {
                    self.selectedStores(normalizedStores);
                    return;
                }

                self.lastSelectedStores = normalizedStores.slice();
                transferPrompt.selectedStores(normalizedStores);
            });

            transferPrompt.storeFilter.subscribe(function (storeId) {
                self.setSelectedStoresFromFilter(storeId);
            });



        },

        /** @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: self.entityType,
                    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.setSelectedStoresFromFilter(storeId);
                transferPrompt.initialized(true);
            } else {
                self.selectedFields(transferPrompt.selectedFields());
                self.selectAllPromptFields(transferPrompt.selectAllPromptFields());
                self.selectedStores(self.normalizeSelectedStores(transferPrompt.selectedStores()));
            }
        },

        /**
         * Set selected stores from the active grid store filter.
         *
         * @param {String|Number} storeId
         * @returns {void}
         */
        setSelectedStoresFromFilter: function (storeId) {
            var selectedStores = [String(storeId || 0)];

            self.lastSelectedStores = selectedStores.slice();
            self.selectedStores(selectedStores);
            transferPrompt.selectedStores(selectedStores);
        },

        /**
         * Normalize selected stores.
         *
         * Keep "All store views" (store id 0) selected even when concrete store views
         * are selected. Only cast values to strings and remove duplicates.
         *
         * @param {Array} selectedStores
         * @returns {Array}
         */
        normalizeSelectedStores: function (selectedStores) {
            var stores = (selectedStores || []).map(function (storeId) {
                return String(storeId);
            });

            return stores.filter(function (storeId, index) {
                return stores.indexOf(storeId) === index;
            });
        },

        /**
         * 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);
            }
        }
    });
});
