/*
 *  Copyright 2019 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.
 */

/**
 * Apogee export actions
 * @private
 */
Ext.define('Ametys.plugins.odfsync.apogee.ws.ApogeeExportButtonActions', {
    singleton: true,
    
    /**
     * @protected
     * Name of the connector
     * @return {String} the name of the connector
     */
    _getName: function()
    {
        return "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_APOGEE_LABEL}}";
    },
    
    /**
     * @protected
     * Callback to call after the export
     * @param {Object} report The export report
     */
    _exportCB: function(report)
    {
        var status = report["status"];
        if (status == "CONTENT_DATA_INVALID")
        {
            this._notifyResult("error", report, "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_APOGEE_ERROR_DIALOG_DATA_MSG}}<br/>" + this._buildResultMessage(report) + "<br/>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_ERROR_KNOWN_SHOW_MORE_MSG}}");
        }
        else if (status == "CONTENT_STRUCTURE_INVALID")
        {
            this._notifyResult("error", report, "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_APOGEE_ERROR_STRUCTURE_MSG}}<br/>" + this._buildResultMessage(report) + "<br/>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_ERROR_KNOWN_SHOW_MORE_MSG}}");
        }
        else if (status == "ERROR")
        {
            this._notifyResult("error", report, this._buildResultMessage(report) + "<br/>{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_ERROR_UNKNOWN_SHOW_MORE_MSG}}");
        }
        else if (status == "OK")
        {
            this._notifyResult("info", report, this._buildResultMessage(report));
        }
    },
    
    /**
     * @protected
     * Add the problem types to the message
     * @param {Object} problemsEncountered List of problems
     */
    _addTheProblemTypes: function(problemsEncountered)
    {
        return "";
    },
    
    /* FIXME COMMON CODE WITH ApogeExportButtonActions */
    
    /**
    * Action function to be called by the controller.
    * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
    */
    act: function (controller)
    {
        var target = controller.getMatchingTargets()[0]; // no multiselection
        var parameters = target.getParameters();
        this._notify('info', Ext.String.format("{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_MSG}}", this._getName(), this._buildProgramLink(parameters.id, parameters.title)));
        this._export(controller, parameters.id);
    },
    
    /**
     * @protected
     * Export to external connector
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     * @param {String} contentId The content id to export
     */
    _export: function(controller, contentId)
    {
        controller.serverCall(
                'exportProgram', 
                [contentId], 
                Ext.bind(this._exportCB, this),
                { refreshing: true }
        );
    },
    
    /**
     * @private
     * Build the link to the content tool
     * @param {String} contentId The content identifier
     * @param {String} contentTitle The content title
     * @return {String} the link to the content tool
     */
    _buildProgramLink: function(contentId, contentTitle)
    {
        return Ext.String.format(
            "<a href=\"javascript:void(0)\" onclick=\"parent.Ametys.tool.ToolsManager.openTool('uitool-content', {id:'{0}'})\">{1}</a>",
            contentId,
            contentTitle
        );
    },
    
    /**
     * @protected
     * Notify the message
     * @param {String} statusType The notification type (info, warn, error)
     * @param {String} message The message into the notification
     */
    _notify: function(statusType, message)
    {
        Ametys.notify({
            type : statusType,
            iconGlyph: 'ametysicon-system-sgbd',
            title: Ext.String.format("{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_TITLE}}", this._getName()),
            description: message
        });
    },
    
    /**
     * @protected
     * Notify the result of the report.
     * @param {String} statusType Level of the result (error, warn, info)
     * @param {Object} report The report
     * @param {String} [addMessage] Additional message to the notification
     */
    _notifyResult: function(statusType, report, addMessage)
    {
        var message = Ext.String.format(
            this._getStartMessage(statusType),
            this._buildProgramLink(report["contentId"], report["contentTitle"]),
            this._getName()
        );
        
        if (addMessage)
        {
            message += " " + addMessage;
        }
        
        this._notify(statusType, message);
    },
    
    /**
     * @private
     * Build the start message of the notification from the status
     * @param {String} statusType The notification status
     * @return {String} The required start message
     */
    _getStartMessage: function(statusType)
    {
        if (statusType == "error")
        {
            return "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_ERROR_MSG}}";
        }
        else if (statusType == "warn")
        {
            return "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_WARN_MSG}}";
        }
        return "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_OK_MSG}}";
    },
    
    /**
     * @private
     * Build result message
     * @param {Object} report The export report
     */
    _buildResultMessage: function(report)
    {
        var message = "";

        // Si on a rencontré des problèmes connus
        var problemsEncountered = report["problemsEncountered"] || [];
        if (problemsEncountered.length >= 1)
        {
            message = "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_PROBLEMS_MSG}}";
            message += this._addTheProblemTypes(problemsEncountered);
        }
        
        message += this._extractIfUseful(report, "nbExported", "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_NB_EXPORTED_MSG}}");
        message += this._extractIfUseful(report, "nbPartlyExported", "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_NB_PARTLY_EXPORTED_MSG}}");
        message += this._extractIfUseful(report, "nbNotExported", "{{i18n plugin.odf-sync:PLUGINS_ODF_SYNC_EXPORT_NOTIFY_NB_NOT_EXPORTED_MSG}}");
        
        return message;
    },
    
    /**
     * @private
     * Extract value from report and display it if useful.
     * @param {Object} report The export report
     * @param {String} fieldName The field to extract
     * @param {Object} message The message
     * @return {String} The message with the field value or and empty string
     */
    _extractIfUseful: function(report, fieldName, message)
    {
        var fieldValue = report[fieldName];
        if (fieldValue > 0)
        {
            return message + " " + fieldValue + "<br/>";
        }
        return "";
    }
});