/*
 *  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.
 */
/**
 * Singleton class defining the actions on reports
 * @private
 */
Ext.define('Ametys.plugins.cms.reports.ReportsActions', {
	singleton: true,
	
	/**
	 * Action to ignore reports
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	ignore: function (controller)
	{
		var targets = controller.getMatchingTargets();
		
		if (targets.length > 0)
		{
			Ametys.Msg.confirm("{{i18n PLUGINS_CMS_CONTENT_IGNORE_REPORTS_CONFIRM_TITLE}}", 
					"{{i18n PLUGINS_CMS_CONTENT_IGNORE_REPORTS_CONFIRM_DESCRIPTION}}", 
					Ext.bind(this._doIgnore, this, [controller, targets], 1),
					this
			);
		}
	},
	
	/**
	 * Callback function invoked after the #ignore confirm box is closed
	 * @param {String} answer Id of the button that was clicked
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the #act function
	 * @param {Ametys.message.MessageTarget[]} targets The registered targets
	 * @private
	 */
	_doIgnore: function (answer, controller, targets)
	{
		if (answer == 'yes')
		{
			var reportedObjects = [];
			for (var i=0; i < targets.length; i++)
			{
                var target = targets[i];
                if (target.getId() == Ametys.message.MessageTarget.CONTENT)
                {
                    reportedObjects.push({
                        contentId: target.getParameters().id
                    });
                }
                else if (target.getId() == Ametys.message.MessageTarget.COMMENT)
                {
                    reportedObjects.push({
                        contentId: target.getParameters().content,
                        commentId: target.getParameters().id
                    });
                }
			}
			
			controller.serverCall('ignoreReports', [reportedObjects], Ext.bind(this._ignoreCb, this), 
			{
		  		errorMessage: {
		  			msg: "{{i18n PLUGINS_CMS_CONTENT_IGNORE_REPORTS_UNKNOWN_ERROR}}",
		  	  		category: 'Ametys.plugins.cms.reports.ReportsActions.ignore'
		  	  	}
			});
		}
	},
	
	/**
	 * @private
	 * Callback function called after ignoring reports
	 * @param {Object[]} response The server's response in JSON.
	 */
	_ignoreCb: function (response)
	{
		var errorMsg = '';
		errorMsg += this._getErrorMsg("{{i18n PLUGINS_CMS_CONTENT_REPORTS_ERROR_UNKNOWN_CONTENTS}}", response['unknown-contents'], 'id');
		errorMsg += this._getErrorMsg("{{i18n PLUGINS_CMS_CONTENT_REPORTS_ERROR_NORIGHT_CONTENTS}}", response['noright-contents'], 'title');
		errorMsg += this._getErrorMsg("{{i18n PLUGINS_CMS_CONTENT_REPORTS_ERROR_UNCOMMENTABLE_CONTENTS}}", response['uncommentable-contents'], 'title');
        errorMsg += this._getErrorMsg("{{i18n PLUGINS_CMS_CONTENT_REPORTS_ERROR_UNREPORTABLE_CONTENTS}}", response['unreportable-contents'], 'title');
		errorMsg += this._getErrorMsg("{{i18n PLUGINS_CMS_CONTENT_REPORTS_ERROR_UNKNOWN_COMMENTS}}", response['unknown-comments'], 'contentTitle');
		
		if (errorMsg.length > 0)
		{
			Ametys.log.ErrorDialog.display({
				title: "{{i18n PLUGINS_CMS_CONTENT_IGNORE_REPORTS_ERRORS_TITLE}}",
				text: "{{i18n PLUGINS_CMS_CONTENT_IGNORE_REPORTS_ERRORS_DESC}}",
				details: errorMsg,
				category: 'Ametys.plugins.cms.comment.CommentActions.ignore'
			});
		}
		
		var targets = [];
		
		var contentsWithIgnoredReports = response['contents-with-ignored-reports'];
		for (var i=0; i < contentsWithIgnoredReports.length; i++)
		{
			targets.push({
				id: Ametys.message.MessageTarget.CONTENT,
				parameters: { 
					ids: [contentsWithIgnoredReports[i].id]
				}
			});
		}
        
        var commentsWithIgnoredReports = response['comments-with-ignored-reports'];
        for (var i=0; i < commentsWithIgnoredReports.length; i++)
        {
            targets.push({
                id: Ametys.message.MessageTarget.COMMENT,
                parameters: { 
                    id: commentsWithIgnoredReports[i].id,
                    content: commentsWithIgnoredReports[i].contentId,
                    reportsCount: 0
                }
            });
        }
		
		if (targets.length > 0)
		{
			Ext.create("Ametys.message.Message", {
				type: Ametys.message.Message.MODIFIED,
				targets: targets
			});
		}
	},
    
    /**
     * @private
     * Constructs the error message
     * @param {String} intro The introduction text
     * @param {Object[]} elmts The elements in error
     * @param {String} name The attribute to display for elements in error
     */
    _getErrorMsg: function (intro, elmts, name)
    {
        if (elmts.length > 0)
        {
            var elmt = [];
            for (var i=0; i < elmts.length; i++)
            {
                elmt.push(elmts[name])
            }   
            
            return intro + elmt.join(', ') + '<br/>';
        }
        return '';
    }
});