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

/**
 * This tool is used to configure a skin.
 * @private
 */
Ext.define('Ametys.plugins.web.skin.SkinConfigurationTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @private
	 * @property {Ametys.form.ConfigurableFormPanel} _formPanel The form for editing skin configuration
	 */
	
	/**
	 * @private
	 * @property {String} _skinId The skin identifier
	 */
	
	/**
	 * @private
	 * @property {String} _mode The configuration mode : 'new' if the skin was not yet created (import is processing) or 'edit' if the skin already exists.
	 */
	
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	createPanel: function ()
	{
		this._formPanel = Ext.create('Ametys.form.ConfigurableFormPanel', {
			cls: 'config',

			tableOfContents: true,
            'tab-policy-mode': 'inline',
            
			listeners: {
				'inputfocus': Ext.bind(this.sendCurrentSelection, this),
				'testresultschange': Ext.bind(this.sendCurrentSelection, this)
			}
		});
		
		return this._formPanel;
	},
	
	/**
	 * @inheritdoc
	 * @param {Object} params The tool's parameters
	 * @param {String} params.id The skin identifier
	 * @param {String} [params.tempDir] The name of temporary directory where the skin was temporally uploaded during import process. This is only required when the skin was not yet created.
	 * @param {String} [params.skinDir] The name of skin directory into temporary directory. This is only required when the skin was not yet created.
	 */
	setParams: function (params)
	{
		this.callParent(arguments);
		this._skinId = params.id;
		
		this._mode = Ext.isEmpty(params.tempDir) ? 'edit' : 'new';
		
		this._skinTempPath = params.tempDir + '/' + params.skinDir;
		this._getConfigurationParameters(params.tempDir, params.skinDir);
		
		var toolTitle = "{{i18n PLUGINS_WEB_ADMINISTRATOR_SKINS_CONFIGURE_TITLE}}";
		toolTitle += params.skinTitle ? params.skinTitle + " (" + this._skinId + ")" : this._skinId;
		this.setTitle(toolTitle);
	},
	
	/**
	 * Get the configuration mode : 'new' if the skin was not yet created (import is processing) or 'edit' if the skin already exists.
	 * @return {String} the mode
	 */
	getMode: function ()
	{
		return this._mode;
	},
	
	/**
	 * Get the configuration mode : 'new' if the skin was not yet created (import is processing) or 'edit' if the skin already exists.
	 * @return {String} the mode
	 */
	getSkinTempPath: function ()
	{
		return this._skinTempPath;
	},
	
	
	/**
	 * Get the configuration parameters in order to initialize the form panel with a server call
	 * @param {String} tempDir The name of temporary directory where the skin was temporally uploaded. Can be null if the skin already exists.
	 * @param {String} skinDir The name of skin directory. Can be null.
	 */
	_getConfigurationParameters: function(tempDir, skinDir)
	{
		Ametys.data.ServerComm.send({
			plugin: 'web', 
			url: "skin/config", 
			parameters: {
				skinName: this._skinId,
				tempDir: tempDir, // can be null
				skinDir: skinDir // can be null
			}, 
			responseType: 'text',
			priority: Ametys.data.ServerComm.PRIORITY_MAJOR, 
			callback: {
		        handler: this._getConfigurationParametersCb,
		        scope: this
		    },
		    errorMessage: {msg: "{{i18n PLUGINS_WEB_ADMINISTRATOR_SKINS_CONFIGURE_ERROR}}", category: this.self.getName()},
		    waitMessage: true
		});
	},
	
	/**
	 * @private
	 * Callback for the retrieving of site configuration parameters
	 * @param {Object} response the server's response
	 * @param {Object} response.parameters the site's parameters
	 * @param {Object} response.values the values of site's parameters
	 */
	_getConfigurationParametersCb: function(response)
	{
		var result = Ext.JSON.decode(Ext.dom.Query.selectValue("", response));
		
		// Initialize the form panel
		this._formPanel.configure(result.parameters.elements);
		this._formPanel.setValues(result.values);
		
		this._formPanel.on({
			afterlayout: {fn: this._focusForm, scope: this, single: true} 
		});
	},
	
	/**
	 * @private
	 * Focuses the form panel
	 */
	_focusForm: function()
	{
		this._formPanel.focus();
	},
	
	sendCurrentSelection: function()
	{
		Ext.create("Ametys.message.Message", {
			type: Ametys.message.Message.SELECTION_CHANGED,
			targets: {
				id: this._mode == 'new' ? Ametys.message.MessageTarget.TEMP_SKIN : Ametys.message.MessageTarget.SKIN,
				parameters: {
					id: this._skinId
				},
				subtargets : {
					id: Ametys.message.MessageTarget.SKIN_CONFIGURATION,
					parameters: {},
					subtargets: [ this._formPanel.getMessageTargetConf() ]
				}
			}
		});
	},
	
	close: function (manual)
    {
		if (manual) // TODO && this.isDirty()
		{
		    var confirmMsg = this._mode == 'new' ? "{{i18n PLUGINS_WEB_ADMINISTRATOR_SKINS_UNSAVE_CONFIG_IMPORT_CONFIRM_DESC}}" : "{{i18n PLUGINS_WEB_ADMINISTRATOR_SKINS_UNSAVE_CONFIG_IMPORT_CONFIRM_DESC}}",
	            args = arguments;
		    
			Ametys.Msg.confirm("{{i18n PLUGINS_WEB_ADMINISTRATOR_SKINS_UNSAVE_CONFIG_CONFIRM_TITLE}}",
					confirmMsg,
					function (answer) {
		                if (answer == 'yes')
		                {
		                    this.superclass.close.apply(this, args);
		                }
		            },
					this
			);
			return;
		}
		
		this.callParent(arguments);
    },
    
    /**
     * Close tool without saving if answer=yes
     * @param {String} answer User answer.
     */
    _unsaveConfirm: function (answer)
    {
    	if (answer == 'yes')
        {
    		// Close tool
            this.close();
        }
    }
    
});

Ext.define("Ametys.message.SkinConfigurationMessageTarget",
{
	override: "Ametys.message.MessageTarget",
	statics: 
	{
		/**
		 * @member Ametys.message.MessageTarget
		 * @readonly
		 * @property {String} SKIN_CONFIGURATION The target of the message is the site configuration form  
		*/
		SKIN_CONFIGURATION: "skin-configuration"
	}
});