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

define([
    'jquery',
    'underscore',
    'mage/translate',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/error-messages',
    'Magento_Ui/js/modal/confirm'
], function (
    $,
    _,
    $t,
    keywordAnalysis,
    errorMessagesModel,
    confirm
) {
    'use strict';

    /**
     * Lock pipeline request
     *
     * @param {Object} self
     * @param {string} pipelineId
     *
     * @returns {void}
     */
    function lockPipelineRequest(self, pipelineId)
    {
        $('#wtai-loader-'+pipelineId).show();
        self.ongoingProcessing(true);
        $.ajax({
            url: self.lockPipelineUrl,
            type: 'POST',
            data: {
                'store_id': self.storeId(),
                'record_id': self.recordId(),
                'entity_type': self.entityType,
                'pipeline_id': pipelineId
            },
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                if (response.success === true) {
                    let optimizationData = keywordAnalysis.optimizationData();
                    let pipelines = optimizationData.pipelines;
                    let index = pipelines.findIndex(pipeline => pipeline.id === pipelineId);
                    if (index !== -1) {
                        pipelines[index].locked = true;
                    }
                    optimizationData.pipelines = pipelines;
                    keywordAnalysis.optimizationData(optimizationData);
                }
            }
        }).always(function () {
            $('#wtai-loader-'+pipelineId).hide();
            self.ongoingProcessing(false);
        });
    }

    /**
     * Unlock pipeline request
     *
     * @param {Object} self
     * @param {string} pipelineId
     *
     * @returns {void}
     */
    function unlockPipelineRequest(self, pipelineId)
    {
        $('#wtai-loader-'+pipelineId).show();
        self.ongoingProcessing(true);
        $.ajax({
            url: self.unlockPipelineUrl,
            type: 'POST',
            data: {
                'store_id': self.storeId(),
                'record_id': self.recordId(),
                'entity_type': self.entityType,
                'pipeline_id': pipelineId
            },
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                if (response.success === true) {
                    let optimizationData = keywordAnalysis.optimizationData();
                    let pipelines = optimizationData.pipelines;
                    let index = pipelines.findIndex(pipeline => pipeline.id === pipelineId);
                    if (index !== -1) {
                        pipelines[index].locked = false;
                    }
                    optimizationData.pipelines = pipelines;
                    keywordAnalysis.optimizationData(optimizationData);
                }
            }
        }).always(function () {
            $('#wtai-loader-'+pipelineId).hide();
            self.ongoingProcessing(false);
        });
    }

    /**
     * Delete keyword pipeline
     *
     * @param {Object} self
     * @param {string} pipelineId
     *
     * @returns {void}
     */
    function deleteKeywordPipeline(self, pipelineId)
    {
        confirm({
            content: $t('Are you sure you want to delete this pipeline?'),
            modalClass: 'wtai-modal wtai-confirm-modal wtai-delete-pipeline-modal',
            overlayClass: 'modals-overlay wtai-delete-pipeline-overlay',
            actions: {
                confirm: function () {
                    deletePipelineRequest(self, pipelineId);
                },
                cancel: function () {
                    $('.modals-overlay.wtai-delete-pipeline-overlay').remove();
                },
                always: function () {
                    $('.modals-overlay.wtai-delete-pipeline-overlay').remove();
                }
            },
            buttons: [{
                text: $t('Cancel'),
                class: 'action-secondary action-dismiss',
                click: function (event) {
                    $('.wtai-delete-pipeline-overlay').remove();
                    this.closeModal(event);
                }
            }, {
                text: $t('Delete'),
                class: 'action-primary action-accept',
                click: function (event) {
                    $('.wtai-delete-pipeline-overlay').remove();
                    this.closeModal(event, true);
                }
            }],
            closed: function () {
                $('.wtai-delete-pipeline-overlay').remove();
            }
        });
    }

    /**
     * Delete pipeline request
     *
     * @param {Object} self
     * @param {string} pipelineId
     * @param {boolean} fromSaveEditPipeline
     *
     * @returns {void}
     */
    function deletePipelineRequest(self, pipelineId, fromSaveEditPipeline = false)
    {
        self.ongoingProcessing(true);
        if (!fromSaveEditPipeline) {
            $('#wtai-loader-' + pipelineId).show();
        } else {
            $('.wtai-edit-pipeline-loading-mask').show();
        }

        var keywordsToRemove = [];
        var optimizationData = keywordAnalysis.optimizationData();
        var pipeline = optimizationData.pipelines.find(pipeline => pipeline.id === pipelineId);
        for (var difficulty in pipeline.keywords) {
            keywordsToRemove.push(pipeline.keywords[difficulty]);
        }

        $.ajax({
            url: self.deletePipelineUrl,
            type: 'POST',
            data: {
                'store_id': self.storeId(),
                'record_id': self.recordId(),
                'entity_type': self.entityType,
                'pipeline_id': pipelineId
            },
            dataType: 'json',
            showWriteTextAILoader: fromSaveEditPipeline,
            showEditPipelineLoader: fromSaveEditPipeline,
            success: function (response) {
                if (response.success) {
                    var optimizationData = keywordAnalysis.optimizationData();
                    var pipelines = optimizationData.pipelines;
                    var keywords = optimizationData.keywords;
                    var index = pipelines.findIndex(pipeline => pipeline.id === pipelineId);
                    var isAutogenerated = pipelines[index].autogenerated;
                    pipelines.splice(index, 1);
                    optimizationData.pipelines = pipelines;
                    
                    if (typeof response.api_response.availableClustersToRestore !== 'undefined') {
                        optimizationData.availableClustersToRestore = response.api_response.availableClustersToRestore;
                    }
                    
                    for (var i = 0; i < keywordsToRemove.length; i++) {
                        if (!keywords.some(keyword => keyword.keyword === keywordsToRemove[i].keyword)) {
                            keywords.push(keywordsToRemove[i]);
                        }
                    }
                    optimizationData.keywords = keywords;
                    keywordAnalysis.optimizationData([]);
                    keywordAnalysis.optimizationData(optimizationData);
                    self.getOptimization();
                } else {
                    if (typeof response.error !== 'undefined') {
                        errorMessagesModel.messages.push(response.error);
                    }
                }
            }
        }).always(function () {
            $('#wtai-loader-' + pipelineId).hide();

            if (fromSaveEditPipeline) {
                self.closeEditPipeline();
                $('.wtai-edit-pipeline-loading-mask').hide();
            }
            self.ongoingProcessing(false);
        });
    }

    /**
     * Is pipeline locked
     *
     * @param {string} id
     */
    function isPipelineLocked(id)
    {
        let optimizedData = keywordAnalysis.optimizationData();
        let pipeline = optimizedData.pipelines.find(pipeline => pipeline.id === id);
        if (pipeline) {
            if (pipeline.autogenerated === true) {
                return pipeline.locked;
            }
        }
        return false;
    }

    /**
     * Edit keyword pipeline
     *
     * @param {Object} self
     * @param {string} id
     *
     * @returns {void}
     */
    function editPipeline(self, id)
    {
        var editPipelineContents = $(self.selectors.editPipelineContainer);
        editPipelineContents.appendTo($('#wtai-wrapper-'+id));
        var pipelineList = keywordAnalysis.optimizationData().pipelines;
        if (pipelineList) {
            var pipelineToEdit = pipelineList.find(pipeline => pipeline.id === id);
            var pipelineCopy = JSON.parse(JSON.stringify(pipelineToEdit));
            self.editKeywordPipeline([]);
            self.editKeywordPipeline(pipelineCopy);
            self.editKeywordPipelineVisible(true);
        }
    }

    /**
     * Is pipeline edit
     *
     * @param {Object} self
     * @param {string} id
     *
     * @returns {boolean}
     */
    function isPipelineActiveEdit(self, id)
    {
        var editPipeline = self.editKeywordPipeline();
        if (editPipeline.id === undefined) {
            return false;
        }
        if (editPipeline.id === id) {
            return true;
        }
        return false;
    }

    return {
        lockPipelineRequest: lockPipelineRequest,
        unlockPipelineRequest: unlockPipelineRequest,
        deleteKeywordPipeline: deleteKeywordPipeline,
        deletePipelineRequest: deletePipelineRequest,
        isPipelineLocked: isPipelineLocked,
        editPipeline: editPipeline,
        isPipelineActiveEdit: isPipelineActiveEdit
    };
});