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

define([
    'jquery',
    'ko',
    'uiComponent',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields'
], function (
    $,
    ko,
    Component,
    textFieldsUtils
) {
    'use strict';

    return Component.extend({
        defaults: {
            clusterCount: 4,
            triggerAction: '',
            triggerActionNPosition: 1,
            triggerActionAfterNDays: 1,
            automaticTextOptimization: '',
            productFields: [],
            categoryFields: [],
            allProductFieldsSelected: false,
            allCategoryFieldsSelected: false,
            triggerActionNone: false,
            isTriggerActionAfterNDays: false,
            isTriggerActionNPosition: false,
            triggerActionSelector: '[name="trigger_action"]'
        },

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

            self = this;
            
            this.initTriggerActionValiation();
            this.initSpinner();
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'clusterCount',
                    'triggerActionNPosition',
                    'triggerActionAfterNDays',
                    'automaticTextOptimization',
                    'productFields',
                    'categoryFields',
                    'allProductFieldsSelected',
                    'allCategoryFieldsSelected',
                    'triggerAction',
                    'triggerActionNone',
                    'isTriggerActionAfterNDays',
                    'isTriggerActionNPosition'
                ]);

            this.disableATO = ko.computed({
                read: function () {
                    return false;
                }.bind(this)
            });

            this.disableTextTypes = ko.computed({
                read: function () {
                    return false;
                }.bind(this)
            });

            this.allProductFieldsSelected = ko.computed({
                read: function () {
                    const productFields = this.productFields() || [];
                    const allProductFields = [...this.allProductFields] || [];
                    return productFields.length === allProductFields.length;
                }.bind(this),
                write: function (value) {
                    const allProductFields = [...this.allProductFields ]|| [];
                    const fields = value ? allProductFields : [];
                    this.productFields(fields);
                }.bind(this)
            }, this);

            this.allCategoryFieldsSelected = ko.computed({
                read: function () {
                    const categoryFields = this.categoryFields() || [];
                    const allCategoryFields = [...this.allCategoryFields] || [];
                    return categoryFields.length === allCategoryFields.length;
                }.bind(this),
                write: function (value) {
                    const allCategoryFields = [...this.allCategoryFields] || [];
                    const fields = value ? allCategoryFields : [];
                    this.categoryFields(fields);
                }.bind(this)
            }, this);

            return this;
        },

        /**
         * Initialize trigger action.
         */
        initTriggerActionValiation: function () {
            this.validateTriggerAction();
        },

        /**
         * Initialize spinner.
         */
        initSpinner: function () {
            setTimeout(
                function () {
                    $('.wtai-setup-keywords-settings .wtai-input-number.wtai-cluster-count').spinner({
                        numberFormat: 'n',
                        min: this.minClusterCount,
                        max: this.maxClusterCount
                    });
                    $('.wtai-setup-keywords-settings .wtai-input-number.wtai-trigger-action-n-position').spinner({
                        numberFormat: 'n',
                        min: this.minTriggerActionNPosition,
                        max: this.maxTriggerActionNPosition
                    });
                    $('.wtai-setup-keywords-settings .wtai-input-number.wtai-trigger-action-after-n-days').spinner({
                        numberFormat: 'n',
                        min: this.minTriggerActionNDays,
                        max: this.maxTriggerActionNDays
                    });
                }.bind(this),
                100
            );
        },

        /**
         * Validate number.
         *
         * @param {Object} data
         * @param {Object} event
         *
         * @return {Boolean}
         */
        ensureNumerical: function (data, event) {
            return textFieldsUtils.ensureNumerical(event.key);
        },

        /**
         * Validate min and max fields.
         *
         * @param {Object} data
         * @param {Object} event
         *
         * @return {void}
         */
        validateMinMax: function (data, event) {
            var target = event.target,
                value = Number(target.value),
                min = Number(target.min),
                max = Number(target.max),
                name = target.name;

            const mapping = {
                cluster_count: self.clusterCount,
                trigger_action_n_position: self.triggerActionNPosition,
                trigger_action_n_days: self.triggerActionAfterNDays,
            };

            if (value < min || value > max) {
                const func = mapping[name],
                    val = value < min ? min : max;

                $(target).val(val);
                func(val);
            }
        },

        /**
         * Validate trigger action changed event
         *
         * @return {void}
         */
        validateTriggerAction: function () {
            const triggerAction = this.triggerAction();
            this.triggerActionNone(triggerAction === 'none');
        }
    });
});
