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

/**
 * Singleton class to translate programs.
 * @private
 */
Ext.define('Ametys.plugins.odf.program.ProgramActions', {
    singleton: true,
    
    /**
     * Validate the content
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    validate: function(controller)
    {
        var contentIds = controller.contents || controller.getContentIds();
        
        // Check if the content references non-validated contents (children excluded)
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.odf.workflow.ODFWorkflowHelper",
            methodName: "checkReferences",
            parameters: [contentIds],
            callback: {
                handler: this._checkValidationCb,
                scope: this,
                arguments: [controller]
            },
            waitMessage: "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_CHECK_VALIDATION_ACTION_WAIT}}",
            errorMessage: "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_CHECK_VALIDATION_ACTION_ERROR}}"
        });
    },
    
    /**
     * @private
     * Convert targets to id
     * @param {Ametys.message.MessageTarget[]} targets The targets
     * @return {String[]} The ids
     */
    _convertToIds: function(targets)
    {
        var ids = [];
        Ext.Array.each(targets, function (target) {
            ids.push(target.getParameters().id);
        });
        return ids;
    },
    
    /**
     * @private
     * Callback function after checking content
     * @param {Object} result The result
     * @param {Object[]} args The callback function
     */
    _checkValidationCb: function(result, args)
    {
        if (result.success)
        {
            Ametys.plugins.cms.content.actions.WorkflowAction.doAction(args[0]);
            return;
        }
        
        Ametys.odf.helper.Content.showInvalidatedContents(result.contentsInError, 
            "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_CHECK_VALIDATION_ACTION_TITLE}}", 
            null, 
            result.contentsInError.length == 1 ? "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_CHECK_VALIDATION_ACTION_INVALIDATED_CONTENTS_2}}" : "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_CHECK_VALIDATION_ACTION_INVALIDATED_CONTENTS_2_MULTIPLE}}", 
            "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_CHECK_VALIDATION_ACTION_INVALIDATED_CONTENTS_1}}",
            Ext.Msg.WARNING,
            true,
            function() {
                Ametys.plugins.cms.content.actions.WorkflowAction.doAction(args[0]);
            });
    },
    
    /**
     * Validate the ODF and its referenced ODF contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    globalValidate: function(controller)
    {
        var contentIds = controller.getContentIds();
        
        if (contentIds.length > 0)
        {
            var me = this;
            
            Ametys.Msg.confirm("{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_LABEL}}",
	            "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_CONFIRM}}",
	            function(answer)
	            {
	                if (answer == 'yes')
	                {
                        Ext.create("Ametys.message.Message", {
				            type: Ametys.message.Message.WORKFLOW_CHANGING,
				            
				            targets: {
				                id: Ametys.message.MessageTarget.CONTENT,
				                parameters: { ids: contentIds }
				            }
				        });
        
	                    Ametys.data.ServerComm.callMethod({
			                role: "org.ametys.odf.workflow.ODFWorkflowHelper",
			                methodName: "globalValidate",
			                priority: Ametys.data.ServerComm.PRIORITY_LONG_REQUEST,
			                parameters: [contentIds],
			                callback: {
			                    handler: me._globalValidateCb,
			                    scope: me,
			                    arguments: [contentIds, controller]
			                },
			                waitMessage: false,
			                errorMessage: false
			            });
	                }
	            }
	        );
        }
    },
    
    /**
     * @private
     * Callback function invoke after global validation process
     * @param {Object} response the result 
     * @param {Object[]} args the callback arguments
     */
    _globalValidateCb: function(response, args)
    {   
        var contentIds = args[0];
        
        Ametys.cms.content.ContentDAO.getContents(contentIds, function(contents) {
           
            // Fire workflow changed for all initial contents
	        Ext.create("Ametys.message.Message", {
	            type: Ametys.message.Message.WORKFLOW_CHANGED,
	            
	            targets: {
	                id: Ametys.message.MessageTarget.CONTENT,
	                parameters: { contents: contents }
	            }
	        });
        
            Ext.Array.forEach(contents, function(content) {
                
                var result = response[content.getId()];
            
	            var validatedContents = result['validatedContents'];
	            var contentsInError = result['contentsInError'];
	            var contentsWithRightError = result['contentsWithRightError'];
            
	            if (contentsInError.length == 0 && contentsWithRightError.length == 0)
	            {
	                // Global validation ends with no error
	                var infoMsg = Ext.String.format("{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_SUCCESS}}", content.getTitle());
	                if (validatedContents.length > 1)
	                {
	                    infoMsg += Ext.String.format("{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_NB_VALIDATED_CONTENTS}}", validatedContents.length);
	                }
	                else if (validatedContents.length == 1)
	                {
	                    infoMsg += "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_ONE_VALIDATED_CONTENT}}";
	                }
	                
	                Ametys.notify({
	                    type: 'info',
	                    iconGlyph: 'ametysicon-sign-raw-check',
	                    title: "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_TITLE}}",
	                    description: infoMsg
	                });
	            }
	            else
	            {
	                // Some contents could not be validated
                    var warnMsg = Ext.String.format("{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_WARN}}", content.getTitle());
	                
	                if (contentsInError.length != 0)
	                {
                        warnMsg += "<br/><br/>"
                        warnMsg += "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_INVALIDATED_START}}";
	                    warnMsg += "<ul>";
	                 
	                    Ext.Array.each(contentsInError, function(contentInError) {
	                       var href = "javascript:(function(){parent.Ametys.tool.ToolsManager.openTool('uitool-content', {id:'" + contentInError.id + "'});})()";
	                       warnMsg += '<li><a href="' + href + '">' + contentInError.title + (contentInError.code ? ' (' + contentInError.code + ')' : '') + '</a></li>';
	                    });
	                    warnMsg += "</ul>"
	                    warnMsg += "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_INVALIDATED_END}}";
	                }
	                
	                if (contentsWithRightError.length != 0)
                    {
	                    warnMsg += "<br/><br/>"
                        warnMsg += contentsInError.length != 0 ? "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_RIGHT_INVALIDATED_START_1}}" : "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_RIGHT_INVALIDATED_START_2}}";
                        warnMsg += "<ul>";
                    
                        Ext.Array.each(contentsWithRightError, function(contentInError) {
                            var href = "javascript:(function(){parent.Ametys.tool.ToolsManager.openTool('uitool-content', {id:'" + contentInError.id + "'});})()";
                            warnMsg += '<li><a href="' + href + '">' + contentInError.title + (contentInError.code ? ' (' + contentInError.code + ')' : '') + '</a></li>';
                        });
                        warnMsg += "</ul>"
                    }
	                
	                Ametys.notify({
	                    type: 'warn',
	                    iconGlyph: 'ametysicon-sign-raw-check',
	                    title: "{{i18n PLUGINS_ODF_WORKFLOW_ACTION_GLOBAL_VALIDATION_TITLE}}",
	                    description: warnMsg
	                });
	            }
            });
        });
    },
    
    /**
     * Set the catalog of a program
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    editCatalog: function (controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            Ametys.plugins.odf.catalog.SetCatalogHelper.act({
                id: targets[0].getParameters().id
            });
        }
    }
});