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

define([
    'jquery',
    'uiComponent',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit/transfer/settings'
], function ($, Component, product, transferSettings) {
    'use strict';

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

    return Component.extend({
        defaults: {
            checkboxSelector: '#wtaiEditTransferForm .wtai-transfer-prompt input',
            storeId: 0,
            selectedStores: []
        },

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

            const el = document.querySelector('#wtaiEditTransferForm .wtai-transfer-prompt');
            if (el) {
                $('#wtaiEditTransferForm .wtai-transfer-prompt > *').applyBindings(this);
            }

            self = this;

            this.initStoreId();

            product.storeId.subscribe(function (storeId) {
                self.storeId(Number(storeId));
            });

            this.selectedStores.subscribe(function (selectedStores) {
                transferSettings.selectedStores([]);
                for (let key in selectedStores) {
                    if (selectedStores.hasOwnProperty(key)) {
                        transferSettings.selectedStores.push(
                            selectedStores[key]
                        );
                    }
                }
            });

            this.storeId.subscribe(function (id) {
                var storeId = Number(id);

                self.storeId(storeId);
                self.updateSelectedStores(storeId);
            });
        },

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

            return this;
        },

        /**
         * Init store id and checkboxes checked
         */
        initStoreId: function () {
            var storeId = Number(product.storeId());

            this.storeId(storeId);
            this.updateSelectedStores(storeId);

            transferSettings.selectedStores([]);
            transferSettings.selectedStores.push(storeId);
        },

        /**
         * Update selected stores
         *
         * @param {string} storeId
         * @returns {void}
         */
        updateSelectedStores: function (storeId) {
            this.selectedStores([]);
            this.selectedStores.push(storeId.toString());
        },

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