/*
 *  Copyright 2022 Anyware Services
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * This tool does display the missing data for the export of a content
 * @private
 */
Ext.define('Ametys.plugins.odfsync.export.ExportStatusTool', {
    extend: "Ametys.tool.SelectionTool",
    
    /**
     * @cfg {String} _exportName The name of the connector
     */
    _exportName: null,
    
    /**
     * @cfg {String} _exportErrorInvalidStructure The component i18n key of the error invalid structure
     */
    _exportErrorInvalidStructure: null,
    
    /**
     * @protected
     * @property {String[]} _contentsOfStructure The contents in the structure of the handled content
     */
    
    constructor: function(config)
    {
        this.callParent(arguments);
        
        this._exportName = config["export-name"];
        this._exportErrorInvalidStructure = config["export-error-invalid-structure"];
        this._contentsOfStructure = [];
        
        Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onChange, this);
        Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onChange, this);
    },

    /**
     * @private
     * Call when a content is modified or deleted
     * @param {Object} message the selection message.
     */
    _onChange: function(message)
    {
        var contentTargets = message.getTargets(Ametys.message.MessageTarget.CONTENT);
        if (contentTargets != null && contentTargets.length > 0)
        {
            var parameters = contentTargets[0].getParameters()
            if (this._contentsOfStructure.indexOf(parameters.id) != -1)
            {
                this.showOutOfDate(true);
            }
        }
    },

    _isRefreshNeeded: function (message)
    {
        if (this.callParent(arguments))
        {
            var contentTargets = message.getTargets(Ametys.message.MessageTarget.CONTENT);
            if (contentTargets != null && contentTargets.length > 0)
            {
                var parameters = contentTargets[0].getParameters()
                if (parameters.types[0] == "org.ametys.plugins.odf.Content.program")
                {
                    if (this._contentId != parameters.id)
                    {
                        this._contentId = parameters.id;
                        this._contentTitle = parameters.title;
                        this._contentsOfStructure = [];
                        return true;
                    }
                }
            }
        }
        return false;
    },

    createPanel: function()
    {
        return Ext.create('Ext.Panel', {
            border: false,
            scrollable: false,
            cls: 'export-status-tool',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            items: [{
                        xtype: 'component',
                        itemId: 'no-selection',
                        style: {
                            textAlign: 'center'
                        },
                        ui: 'tool-hintmessage',
                        html: '',
                        hidden: true
                    },
                    {
                        flex: 1,
                        border: false,
                        scrollable: true,
                        xtype: 'panel',
                        itemId: 'missing-attributes',
                        html: '',
                        bodyStyle: {
                            padding: '5px'
                        },
                        dockedItems:[
                            {
                                dock: 'top',
                                itemId: 'content-info',
                                ui: 'tool-hintmessage',
                                xtype: 'component',
                                style: {
                                    textAlign: 'center'
                                },
                                html: ''
                            }
                        ]
                    }
            ]
        });
    },

    setNoSelectionMatchState: function (message)
    {
        this.callParent(arguments);

        if (this._contentId == null)
        {
            this.getContentPanel().down("#missing-attributes").hide();
            this.getContentPanel().down("#no-selection").update(message);
            this.getContentPanel().down("#no-selection").show();
        }
    },
    
    /**
     * @protected
     * Call the method to refresh the tool
     */
    _callMethod: function()
    {
        this.serverCall(
            'getExportReportInfo', 
            [this._contentId], 
            Ext.bind(this._displayReport, this),
            { refreshing: true }
        );
    },
    
    refresh: function ()
    {
        this.showRefreshing();
        this.getContentPanel().down("#missing-attributes").show();
        this.getContentPanel().down("#no-selection").hide();

        if (!this._contentId)
        {
            var contentTarget = this.getCurrentSelectionTargets()[0];
            this._contentId = contentTarget.getParameters().id;
            this._contentTitle = contentTarget.getParameters().title;
        }

        var toptitle = Ext.String.format(
                "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_STATUS_HINT}}",
                this._exportName, // Nom affichage du connecteur
                this._contentTitle
            );
        
        this.getContentPanel().items.get(1).down("*[dock='top']").update(toptitle);

        this._callMethod();
    },
    
    /**
     * @private
     * Callback after getting export information
     * @param {Object} report The export report
     */
    _displayReport: function(report)
    {
        var status = report["status"];
        if (status == "ERROR")
        {
            this._displayMessage(
                Ext.String.format(
                    "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_MSG}}",
                    this._exportName // Nom affichage du connecteur
                )
            );
        }
        else if (status == "CONTENT_DATA_INVALID")
        {
            this._displayMessage(this._buildDataInvalidErrorMessage(report));
        }
        else if (status == "CONTENT_STRUCTURE_INVALID")
        {
            this._displayMessage(this._exportErrorInvalidStructure);
        }
        else if (status == "NON_EDITABLE_PROGRAM_ALREADY_EXISTS")
        {
            this._displayMessage("{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_PEGASE_PB_TYPE_PROGRAM_ALREADY_EXIST_MSG}}");
        }
        else if (status == "PROGRAM_IMPOSSIBLE_VERSION")
        {
            this._displayMessage("{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_PEGASE_PB_TYPE_PROGRAM_IMPOSSIBLE_VERSION_MSG}}");
        }
        else if (status == "OK")
        {
            this._displayMessage(
                Ext.String.format(
                    "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_TOOL_OK_MSG}}",
                    this._exportName // Nom affichage du connecteur
                )
            );
        }
    },

    /**
     * @private
     * Display a message
     * @param {String} message The message
     */
    _displayMessage: function(message)
    {
        this.getContentPanel().down("#missing-attributes").update(message);
        this.showRefreshed();
    },

    /**
     * @private
     * Build invalid data error message
     * @param {Object} report The export report
     * @return {String} The message with the list of errors
     */
    _buildDataInvalidErrorMessage: function(report)
    {
        var message = Ext.String.format(
                "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_DATA_MSG}}",
                this._exportName // Nom affichage du connecteur
            );
        
        if (!Ext.Object.isEmpty(report["program"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_PROGAM_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["program"]);
        }

        if (!Ext.Object.isEmpty(report["subprogram"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_SUBPROGAM_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["subprogram"]);
        }

        if (!Ext.Object.isEmpty(report["container"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_CONTAINER_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["container"]);
        }

        if (!Ext.Object.isEmpty(report["courselist"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_COURSELIST_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["courselist"]);
        }

        if (!Ext.Object.isEmpty(report["course"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_COURSE_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["course"]);
        }

        if (!Ext.Object.isEmpty(report["orgunit"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_ORGUNIT_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["orgunit"]);
        }

        if (!Ext.Object.isEmpty(report["other"]))
        {
            message += "<p><strong>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_ERROR_OTHER_TITLE}}</strong></p>";
            message += this._buildMandatoryDataErrorMessage(report["other"]);
        }
        return message;
    },

    /**
     * @private
     * Build mandatory data error message
     * @param {Object} report The export report
     * @return {String} The message with the list of errors
     */
    _buildMandatoryDataErrorMessage: function(report)
    {
        var message = '<ul>';
        for (var id in report)
        {
            this._contentsOfStructure.push(id);
            var dataInfo = report[id];

            message += '<li>';
            var href = dataInfo.isTableRef
                ? "javascript:(function(){parent.Ametys.tool.ToolsManager.openTool('uitool-reference-table', {id:'reference-table-search-ui." + dataInfo.contentTypeId + "', contentType:'" + dataInfo.contentTypeId + "', startSearchAtOpening:true});})()"
                : "javascript:(function(){parent.Ametys.tool.ToolsManager.openTool('uitool-content', {id:'" + id + "'});})()";
            message += '<a href="' + href + '">' + (dataInfo.contentTypeLabel ? '[' + dataInfo.contentTypeLabel + '] ' : '') + dataInfo.contentTitle + (dataInfo.contentCode ? ' (' + dataInfo.contentCode + ')' : '') + '</a>';
            message += '<ul>';

            var attributes = dataInfo.attributes.sort();
            for (var i in attributes)
            {
                message += '<li>' + attributes[i] + '</li>';
            }

            message += '</ul>';
            message += '</li>';
        }
        message += '</ul>';

        return message;
    }
});