/*
 *  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 site
 * @private
 */
Ext.define('Ametys.plugins.web.site.SiteConfigurationTool', {
	extend: 'Ametys.tool.Tool',
	
	/**
	 * @private
	 * @property {Ametys.form.ConfigurableFormPanel} _formPanel The form for editing site configuration
	 */
	
	/**
	 * @private
	 * @property {String} _siteName The site name
	 */
	/**
	 * @private
	 * @property {String} _siteId The site ID
	 */
	
	constructor: function(config)
	{
		this.callParent(arguments);
		Ametys.message.MessageBus.on(Ametys.message.Message.DELETED, this._onDeleted, this);
	},
	
	getMBSelectionInteraction: function() 
	{
		return Ametys.tool.Tool.MB_TYPE_ACTIVE;
	},
	
	createPanel: function ()
	{
		this._formPanel = Ext.create('Ametys.form.ConfigurableFormPanel', {
			cls: 'uitool-admin-site-config',

			tableOfContents: true,
            'tab-policy-mode': 'inline',

			listeners: {
				'fieldchange': Ext.bind(this.setDirty, this, [true], false),
				'testresultschange': Ext.bind(this.sendCurrentSelection, this),
				'inputfocus': Ext.bind(this.sendCurrentSelection, this)
			}
		});
		
		return this._formPanel;
	},
	
	setParams: function (params)
	{
		this.callParent(arguments);
		
		if (!this._formPanel._formReady)
		{
			// Do not configure the form panel twice
			this._siteName = params.siteName;
			this._siteId = params.siteId || params.id;
			
			this._getConfigurationParameters();
			
			var toolTitle = "{{i18n PLUGINS_WEB_ADMINISTRATOR_SITES_CONFIGURE_TITLE}}";
			toolTitle += params.siteTitle ? params.siteTitle + " (" + this._siteName + ")" : this._siteName;
			this.setTitle(toolTitle);
		}
	},
	
	/**
	 * Get the configuration parameters in order to initialize the form panel with a server call
	 */
	_getConfigurationParameters: function()
	{
		Ametys.data.ServerComm.send({
			plugin: 'web', 
			url: "administrator/site/config", 
			parameters: {
				siteName: this._siteName
			}, 
			responseType: 'text',
			priority: Ametys.data.ServerComm.PRIORITY_MAJOR, 
			callback: {
		        handler: this._getConfigurationParametersCb,
		        scope: this
		    },
		    errorMessage: {msg: "{{i18n PLUGINS_WEB_ADMINISTRATOR_SITES_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: Ametys.message.MessageTarget.SITE,
				parameters: {
					name: this._siteName,
					id: this._siteId
				},
				subtargets : {
					id: Ametys.message.MessageTarget.SITE_CONFIGURATION,
					parameters: {},
					subtargets: [ this._formPanel.getMessageTargetConf() ]
				}
			}
		});
	},
	
	/**
     * @private
     * Listener on site deletion
     * @param {Ametys.message.Message} message The deletion message
     */
	_onDeleted: function (message)
	{
		var targets = message.getTargets(Ametys.message.MessageTarget.SITE);
		
		for (var i=0; i < targets.length; i++)
        {
            if (this._siteId == targets[i].getParameters().id)
            {
                this.close();
            }
        }
		
	},
	
	close: function (manual)
    {
		if (manual && this.isDirty())
		{
			Ametys.form.SaveHelper.promptBeforeQuit("{{i18n plugin.admin:PLUGINS_ADMIN_CONFIG_DIRTY_CLOSE_MBOX_LABEL}}", 
				    "{{i18n plugin.admin:PLUGINS_ADMIN_CONFIG_DIRTY_CLOSE_MBOX_TEXT}}",
				    null,
				    Ext.bind(this._closeCb, this));
		}
		else
		{
			this.callParent(arguments);
		}
    },
    
    /**
     * Callback for the tool's closing process
     * @param {Boolean} doSave true to save the form before closing the tool, false not to save the form before closing, null to do nothing
     */
    _closeCb: function(doSave)
    {
		if (doSave != null)
		{
			if (doSave)
			{
				var form = this._formPanel;
				Ametys.form.SaveHelper.canSave(form, Ext.bind(Ametys.plugins.web.site.SiteActions._doSave, Ametys.plugins.web.site.SiteActions, [this, form, this._siteName, this._siteId], 1));
			}
			else
			{
				Ametys.plugins.web.site.SiteConfigurationTool.superclass.close.call(this);
			}
		}
    }
});

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