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

/**
 * CRUD actions on thesaurus
 * @private
 */
Ext.define('Ametys.plugins.thesaurus.ThesaurusActions', {
	singleton: true,
	
	/**
	 * Open a thesaurus tool
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	openThesaurus: function (controller)
	{
		Ametys.tool.ToolsManager.openTool(controller.getInitialConfig('opentool-id'), {'id': controller.getInitialConfig('thesaurusId')}); 
	},
	
	/**
	 * This action creates a new thesaurus
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	createThesaurus: function(controller)
	{
		Ametys.plugins.thesaurus.helper.EditLabelDialogBox.open ('ametysicon-books decorator-ametysicon-add64',
				"{{i18n PLUGINS_THESAURUS_NEW_THESAURUS_DIALOG_CAPTION}}",
				"{{i18n PLUGINS_THESAURUS_NEW_THESAURUS_DIALOG_HINT}}",
				Ext.bind (this._doCreateThesaurus, this),
				"{{i18n PLUGINS_THESAURUS_NEW_THESAURUS_DIALOG_DEFAULT_LABEL}}");
	},
	
	/**
	 * Creates a new thesaurus
	 * @param {String} title The title
	 * @private
	 */
	_doCreateThesaurus: function (title)
	{
        Ametys.plugins.thesaurus.ThesaurusDAO.createThesaurus([title], function(result) {
            if (result.success)
            {
                if (result.canCreateMicroThesaurus)
                {
                    // Open microthesaurus creation dialog box after creation
                    Ametys.plugins.thesaurus.ThesaurusActions.createMicrothesaurus(null, result.id);
                }
                else
                {
                    // Restart application to "refresh" the gallery
                    Ametys.plugins.thesaurus.ThesaurusActions.restart();
                }
            }
        });
	},
	
	/**
	 * This action renames a thesaurus
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	renameThesaurus: function(controller)
	{
		var target = controller.getMatchingTargets()[0];
		if (target != null)
		{
			Ametys.plugins.thesaurus.helper.EditLabelDialogBox.open ('ametysicon-books decorator-ametysicon-input',
					"{{i18n PLUGINS_THESAURUS_EDIT_THESAURUS_DIALOG_CAPTION}}",
					null,
					Ext.bind (this._doRenameThesaurus, this, [target.getParameters().id], true),
					target.getParameters().label);
		}
	},
	
	/**
	 * Creates a new thesaurus
	 * @param {String} title The title
	 * @param {String} thesaurusId The id of thesaurus
	 * @private
	 */
	_doRenameThesaurus: function (title, thesaurusId)
	{
		Ametys.Msg.confirm("{{i18n PLUGINS_THESAURUS_RESTART_LABEL}}", 
	   			"{{i18n PLUGINS_THESAURUS_RESTART_CONFIRM}}", 
	   			function(btn) {
					if (btn == 'yes')
					{
						Ametys.plugins.thesaurus.ThesaurusDAO.updateThesaurus([thesaurusId, title]);
					}
					
				}, this
		);
	},
	
	/**
	 * This action delete a thesaurus
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	deleteThesaurus: function(controller)
	{
		var target = controller.getMatchingTargets()[0];
		if (target != null)
		{
			var confirmMsg = Ext.String.format("{{i18n PLUGINS_THESAURUS_DELETE_THESAURUS_CONFIRM}}", target.getParameters().label);
			Ametys.Msg.confirm("{{i18n PLUGINS_THESAURUS_DELETE_THESAURUS_LABEL}}", 
				confirmMsg, 
				function(btn) {
					if (btn == 'yes')
					{
						Ametys.Msg.confirm("{{i18n PLUGINS_THESAURUS_RESTART_LABEL}}", 
					   			"{{i18n PLUGINS_THESAURUS_RESTART_CONFIRM}}", 
					   			function(btn) {
									if (btn == 'yes')
									{
										Ametys.plugins.thesaurus.ThesaurusDAO.deleteThesaurus([target.getParameters().id, target]);
									}
									
								}, this
						);
					}
					
				}, this
			);
		}
	},
	
	/**
	 * The action opens a dialogue box to create a microthesaurus
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 * @param {String} thesaurusId the id of the thesaurus to create the microthesaurus from
	 */
	createMicrothesaurus: function(controller, thesaurusId)
	{
		if (!thesaurusId)
		{
			thesaurusId = controller.getMatchingTargets()[0].getParameters().id;
		}
        
		Ametys.plugins.thesaurus.helper.EditMicrothesaurusDialogBox.open({
            thesaurusId: thesaurusId,
            mode: 'new'
        });
	},
	
	/**
	 * This action edits a microthesaurus
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	editMicrothesaurus: function(controller)
	{
		var target = controller.getMatchingTargets()[0];
		if (target != null)
		{
			var mtTarget = target.getSubtarget(Ametys.message.MessageTarget.MICROTHESAURUS);
			
			if (mtTarget != null)
			{
                Ametys.plugins.thesaurus.helper.EditMicrothesaurusDialogBox.open({
		            label: mtTarget.getParameters().label,
                    microthesaurusId: mtTarget.getParameters().id,
                    thesaurusId: mtTarget.getParameters().thesaurusId,
		            mode: 'edit'
		        });
			}
		}
	},
	
	/**
	 * This action deletes a microthesaurus
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	deleteMicrothesaurus: function(controller) 
	{
		var target = controller.getMatchingTargets()[0];
		if (target != null)
		{
			var mtTarget = target.getSubtarget(Ametys.message.MessageTarget.MICROTHESAURUS);
			
			if (mtTarget != null)
			{
				var confirmMsg = "{{i18n PLUGINS_THESAURUS_DELETE_MICROTHESAURUS_CONFIRM}}" + "<strong>" + mtTarget.getParameters().label + "</strong> ?";
				Ametys.Msg.confirm("{{i18n PLUGINS_THESAURUS_DELETE_MICROTHESAURUS_TITLE}}", 
					confirmMsg, 
					function(btn) {
						if (btn == 'yes')
						{
							Ametys.Msg.confirm("{{i18n PLUGINS_THESAURUS_RESTART_LABEL}}", 
						   			"{{i18n PLUGINS_THESAURUS_RESTART_CONFIRM}}", 
						   			function(btn) {
										if (btn == 'yes')
										{
				                            Ametys.plugins.thesaurus.ThesaurusDAO.deleteMicrothesaurus([mtTarget.getParameters().id, mtTarget]);
										}
								}, this
						   	);
						}
						
					}, this
				);
			}
		}
	},
	
    /**
     * Restart the application to take into account the modifications
     */
	restart: function ()
	{
   		var url = Ametys.getPluginDirectPrefix('admin') + "/restart",
   			result = null,
   			ex = '';
   		
   		var id = Ametys.mask.GlobalLoadMask.mask("{{i18n PLUGINS_THESAURUS_RESTART_LOADING}}");
   		
   		function restart()
   		{
   			try
   			{
   				result =  Ext.Ajax.request({url: url, async: false});   
   			}
   			catch (e)
   			{
   				ex = e;
   			}
   			
   			 Ametys.mask.GlobalLoadMask.unmask(id); 
   			
   			if (result == null)
   			{
   				Ametys.log.ErrorDialog.display({
   					title: "{{i18n PLUGINS_THESAURUS_RESTART_FAILED}}", 
   					text: "{{i18n PLUGINS_THESAURUS_RESTART_FAILED_TEXT}}",
   					details: ex,
   					category: "Ametys.plugins.core.administration.Config.save"
   				});
   				return;
   			}
   			
   			// Reload application
   			document.location.reload(true);
   		}
   		window.setTimeout(restart, 1);
	}
});