/*
 *  Copyright 2018 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 delete orgUnit contents
 * @private
 */
Ext.define('Ametys.plugins.userdirectory.content.DeleteContentAction', {
    singleton: true,
    
    /**
	 * Action function to be called by the controller.
	 * Will delete the contents registered by the controller.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	act: function (controller)
	{
        this._contentIdToDelete = null;
        this._contentTarget = null;
        var contentIds = controller.getContentIds();
        
        if (contentIds.length > 0)
        {
            var contentTargets = controller.getMatchingTargets();
            
            var me = this;
            Ext.Array.forEach (contentTargets, function (contentTarget) {
                if (Ext.Array.contains (contentIds, contentTarget.getParameters().id))
                {
                    me._contentTarget = contentTarget;
                    me._contentIdToDelete = contentTarget.getParameters().id;
                    return false; // stop iteration
                }
            });
            
            if (this._contentTarget)
            {
            	this._deleteOrgUnitContent(controller, this._contentTarget);
            }
        }
	},
	
	/**
	 * Delete single orgUnit with confirmation
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the #act function
     * @param {Ametys.message.MessageTarget} contentTarget The content target to delete
	 * @private
	 */
	_deleteOrgUnitContent: function(controller, contentTarget)
	{
		Ametys.Msg.confirm("{{i18n plugin.cms:CONTENT_DELETE_LABEL}}", 
				"{{i18n plugin.cms:CONTENT_DELETE_CONFIRM}}" + contentTarget.getParameters().title + ' ?', 
				Ext.bind(this._deleteOrgUnitConfirm, this, [controller, contentTarget], 1),
				this
		);
	},
	
	/**
	 * Callback function invoked after the #act 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} contentTarget The content target
	 * @private
	 */
	_deleteOrgUnitConfirm: function (answer, controller, contentTarget)
	{
		if (answer == 'yes')
		{
			controller.serverCall('deleteContents', [[this._contentIdToDelete], {}], Ext.bind(this._deleteOrgUnitCb, this),
			   {
	                priority: Ametys.data.ServerComm.PRIORITY_MAJOR,
					arguments: contentTarget,
					errorMessage: {
							msg: "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_ERROR_MSG}}",
							category: 'Ametys.plugins.userdirectory.content.DeleteContentAction'
					},
					waitMessage: true
		       });
		}
	},
	
	/**
	 * Callback function called after #act is processed.
	 * @param {Object} response The JSON result 
	 * @param {Object} contentTarget The content target
	 * @private
	 */
	_deleteOrgUnitCb: function (response, contentTarget)
	{
        var rootContentDeleted = null;
        
		var deletedContents = response[this._contentIdToDelete]['deleted-contents'];
		if (deletedContents.length > 0)
		{
			for (var i=0; i < deletedContents.length; i++)
			{
	        	if (contentTarget.getParameters().id == deletedContents[i].id)
				{
                    rootContentDeleted = deletedContents[i];
                    
	        		// Remove content from navigation history
	        		Ametys.navhistory.HistoryDAO.removeEntry (deletedContents[i].id);
	        		
	        		// Fires deleted event
	        		Ext.create("Ametys.message.Message", {
	        			type: Ametys.message.Message.DELETED,
                        // we assume that everything is trashed. The only case
                        // of actual deletion should be shared content but we will ignore it
                        // for simplicity
                        parameters : {trashed: true},
	        			targets: contentTarget
	        		});
				}
			}
		}

        this._showReport(response, rootContentDeleted);
	},
	
	/**
	 * Display report after deletion
	 * @param {Object} response The JSON result 
	 * @param {Object} deletedContent The deleted root content. Can be null if the deletion failed.
	 * @private
	 */
	_showReport: function(response, deletedContent)
	{
        if (response[this._contentIdToDelete]['check-before-deletion-failed'])
        {
            // Prerequisites for deletion are not met, display an error message
            var initialContentToDelete = response[this._contentIdToDelete]['initial-content'];
            var referencedContents = response[this._contentIdToDelete]['referenced-contents'];
            var lockedContents = response[this._contentIdToDelete]['locked-contents'];
            var unauthorizedContents = response[this._contentIdToDelete]['unauthorized-contents'];
            
            var message = Ametys.cms.content.ContentDAO._buildErrorMessage(message, [initialContentToDelete], "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_MAIN_CONTENT_ERROR_START}}", "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_MAIN_CONTENT_ERROR_END}}");
            
            message += "<ul>";
            
            if (referencedContents.length > 0)
            {
                message += "<li>" + Ametys.cms.content.ContentDAO._buildErrorMessage("", referencedContents, "{{i18n plugin.cms:CONTENT_DELETE_REFERENCED_CONTENTS}}", ".<br/>{{i18n plugin.cms:CONTENT_DELETE_REFERENCED_CONTENTS_END}}") + "</li>";
            }
            if (lockedContents.length > 0)
            {
	            message += "<li>" + Ametys.cms.content.ContentDAO._buildErrorMessage("", lockedContents, "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_LOCKED_CONTENTS}}") + "</li>";
            }
            if (unauthorizedContents.length > 0)
            {
                message += "<li>" + Ametys.cms.content.ContentDAO._buildErrorMessage("", unauthorizedContents, "{{i18n plugin.cms:CONTENT_DELETE_UNAUTHORIZED_CONTENTS}}") + "</li>";
            }
            message += "</ul>";
            
            Ametys.Msg.show({
                   title: "{{i18n plugin.cms:CONTENT_DELETE_LABEL}}",
                   msg: message,
                   buttons: Ext.Msg.OK,
                   icon: Ext.MessageBox.ERROR
            });
        }
        else
        {
            // The deletion was performed, may be with warnings or errors
            var initialContentToDelete = response[this._contentIdToDelete]['initial-content'];
	        var undeletedContents = response[this._contentIdToDelete]['undeleted-contents'];
	        var referencedContents = response[this._contentIdToDelete]['referenced-contents'];
	        var lockedContents = response[this._contentIdToDelete]['locked-contents'];
	        var unauthorizedContents = response[this._contentIdToDelete]['unauthorized-contents'];
	        if (undeletedContents.length > 0 || lockedContents.length > 0 || unauthorizedContents.length > 0)
	        {
	        	var message = '';
				message = Ametys.cms.content.ContentDAO._buildErrorMessage(message, [initialContentToDelete], "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_MAIN_CONTENT_ERROR_START}}", "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_MAIN_CONTENT_ERROR_END}}");
	            
	            message = Ametys.cms.content.ContentDAO._buildErrorMessage(message, undeletedContents, "{{i18n plugin.cms:CONTENT_DELETE_FAILED_CONTENTS}}");
	            message = Ametys.cms.content.ContentDAO._buildErrorMessage(message, lockedContents, "{{i18n plugin.cms:CONTENT_DELETE_LOCKED_CONTENTS}}");
	            message = Ametys.cms.content.ContentDAO._buildErrorMessage(message, unauthorizedContents, "{{i18n plugin.cms:CONTENT_DELETE_UNAUTHORIZED_CONTENTS}}");
	            
	            // Show error in content deletion
	            Ametys.Msg.show({
	            	buttons: Ext.Msg.OK,
	    			icon: Ext.MessageBox.ERROR,
	    			title: "{{i18n plugin.cms:CONTENT_DELETE_LABEL}}",
	    			msg: message
	    		});
	        }
	        else if (referencedContents.length > 0)
	        {
	        	var	message = "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_MAIN_CONTENT_DELETED}}" + deletedContent.title;
	        	message = Ametys.cms.content.ContentDAO._buildErrorMessage(message, referencedContents, "{{i18n PLUGINS_USER_DIRECTORY_CONTENT_DELETE_MSGBOX_MAIN_CONTENT_REFERENCED}}", ".<br/>{{i18n plugin.cms:CONTENT_DELETE_REFERENCED_CONTENTS_END}}");
	        	
				// Show warning in content deletion
				Ametys.Msg.show({
	    			buttons: Ext.Msg.OK,
	    			icon: Ext.MessageBox.WARNING,
	    			title: "{{i18n plugin.cms:CONTENT_DELETE_LABEL}}",
	    			msg: message
	    		});
	        }
	        else if (deletedContent)
	        {
	            // Notify content deletion
	        	Ametys.Msg.show({
        			buttons: Ext.Msg.OK,
	    			icon: Ext.MessageBox.INFO,
	    			title: "{{i18n plugin.cms:PLUGINS_CMS_NOTIFICATION_DELETE_CONTENT_TITLE}}",
	                msg: Ext.String.format("{{i18n plugin.cms:PLUGINS_CMS_NOTIFICATION_DELETE_CONTENT_DESCRIPTION}}", deletedContent.title)
	            });
	        }
        }
	}
});