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

define([
    'jquery',
    'ko',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/grid/slug-notice',
    'mage/translate'
], function (
    $,
    ko,
    Component,
    _,
    slugNotice,
    $t
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            urls: [],
            categoryIds: [],
            productIds: [],
            storeUrls: []
        },

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

            self = this;

            slugNotice.cmsUrls.subscribe(function (urls) {
                self.urls(urls);
            });

            try {
                this.getCmsUrlsFromUrl();
            } catch (e) {
                console.error(e);
            }
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'urls',
                'categoryIds',
                'productIds',
                'storeUrls'
            ]);

            this.categoryNotice = ko.computed(function () {
                try {
                    var params = new URLSearchParams(window.location.search);
                    var storeId = params.get('wtai-store-id');
                    var recordIds = this.categoryIds();
                    var links = [];
                    
                    /* Check if recordIds is an object or array */
                    if (recordIds && typeof recordIds === 'object') {
                        var cmsUrls = slugNotice.cmsUrls();
                        if (cmsUrls) {
                            cmsUrls = encodeURIComponent(JSON.stringify(cmsUrls));
                        }
                        
                        Object.keys(recordIds).forEach(function (key) {
                            if (key == storeId && self.entityType === 'Category') {
                                /* Skip current store */
                            } else {
                                var idGroup = recordIds[key];
                                if (Array.isArray(idGroup)) {
                                    var encodedIds = idGroup.join(',');
                                    var link = this.categoryLink + '?wtai-record-ids=' + encodedIds +
                                            '&wtai_cms_urls=' + cmsUrls +
                                            '&wtai-store-id=' + key +
                                            '&wtai_category_ids=' + encodeURIComponent(JSON.stringify(recordIds)) +
                                            '&wtai_product_ids=' + encodeURIComponent(JSON.stringify(this.productIds())) +
                                            '&wtai_store_urls=' + encodeURIComponent(JSON.stringify(this.storeUrls()));
                                    links.push($t('<a href="%s" target="_blank">Categories</a> - %t').replace('%s', link).replace('%t', this.storeUrls()[key]));
                                }
                            }
                        }, this);
                    }
                    
                    /* Return all links, one per line */
                    return links.join('<br>');
                } catch (e) {
                    console.error(e);
                    return '';
                }
            }, this);

            this.productNotice = ko.computed(function () {
                try {
                    var params = new URLSearchParams(window.location.search);
                    var storeId = params.get('wtai-store-id');
                    var recordIds = this.productIds();
                    var links = [];
                    
                    /* Check if recordIds is an object or array */
                    if (recordIds && typeof recordIds === 'object') {
                        var cmsUrls = slugNotice.cmsUrls();
                        if (cmsUrls) {
                            cmsUrls = encodeURIComponent(JSON.stringify(cmsUrls));
                        }
                        
                        Object.keys(recordIds).forEach(function (key) {
                            if (key == storeId && self.entityType === 'Product') {
                                /* Skip current store */
                            } else {
                                var idGroup = recordIds[key];
                                if (Array.isArray(idGroup)) {
                                    var encodedIds = idGroup.join(',');
                                    var link = this.productLink + '?wtai-record-ids=' + encodedIds +
                                            '&wtai_cms_urls=' + cmsUrls +
                                            '&wtai-store-id=' + key +
                                            '&wtai_product_ids=' + encodeURIComponent(JSON.stringify(recordIds)) +
                                            '&wtai_category_ids=' + encodeURIComponent(JSON.stringify(this.categoryIds())) +
                                            '&wtai_store_urls=' + encodeURIComponent(JSON.stringify(this.storeUrls()));
                                    links.push($t('<a href="%s" target="_blank">Products</a> - %t').replace('%s', link).replace('%t', this.storeUrls()[key]));
                                }
                            }
                        }, this);
                    }
                    
                    /* Return all links, one per line */
                    return links.join('<br>');
                } catch (e) {
                    console.error(e);
                    return '';
                }
            }, this);

            this.showNotice = ko.computed(function () {
                return this.urls().length > 0 || this.categoryNotice() || this.productNotice();
            }, this);

            return this;
        },

        /**
         * Dismiss the notice
         */
        dismiss: function () {
            slugNotice.cmsUrls([]);
            self.categoryIds([]);
            self.productIds([]);
            self.storeUrls([]);
        },

        /**
         * Get the URL for the slug
         *
         * @param {string} slug
         * @returns {string}
         */
        getUrl: function (slug) {
            return slug;
        },

        /**
         * Get the CMS URLs from the URL
         */
        getCmsUrlsFromUrl: function () {
            var params = new URLSearchParams(window.location.search);
            var cmsUrls = params.get('wtai_cms_urls');
            var categoryIds = params.get('wtai_category_ids');
            var productIds = params.get('wtai_product_ids');
            var storeUrls = params.get('wtai_store_urls');

            if (cmsUrls) {
                cmsUrls = JSON.parse(decodeURIComponent(cmsUrls));
                slugNotice.cmsUrls(cmsUrls);
            }

            this.categoryIds([]);
            if (categoryIds) {
                this.categoryIds(JSON.parse(decodeURIComponent(categoryIds)));
            }

            this.productIds([]);
            if (productIds) {
                this.productIds(JSON.parse(decodeURIComponent(productIds)));
            }

            this.storeUrls([]);
            if (storeUrls) {
                this.storeUrls(JSON.parse(decodeURIComponent(storeUrls)));
            }
        }
    });
});
