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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit/settings',
    'WriteTextAI_WriteTextAI/js/model/edit'
], function ($, Component, _, settings, editData) {
    'use strict';

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

    return Component.extend({
        defaults: {
            guideSteps: false,
            opened: false,
            entityType: 'product'
        },

        isGuideStepsChange: false,

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

            self = this;

            $('.wtai-guide-steps > *').applyBindings(this);

            editData.opened.subscribe(function (opened) {
                self.opened(opened);
            });

            settings.guideSteps.subscribe(function (guideSteps) {
                self.isGuideStepsChange = true;
                self.guideSteps(guideSteps);
                self.isGuideStepsChange = false;
            });

            self.guideSteps.subscribe(function (guideSteps) {
                if (!self.isGuideStepsChange) {
                    self.save(guideSteps);
                }
            });
        },

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

            return this;
        },

        /**
         * Save guide steps checkbox
         *
         * @param {boolean} value
         * @return void
         */
        save: function (value) {
            var url = self.saveUrl;

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    guide_steps: value,
                    entity_type: '',
                    scope: 'edit'
                },
                dataType: 'json',
                showWriteTextAILoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response.message);
                    } else {
                        settings.guideSteps(value);
                    }
                }
            });
        }
    });
});
