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

/**
 * This singleton class is used to edit table properties
 * @private
 */
Ext.define('Ametys.plugins.cms.editor.Tables.Properties', {
	singleton: true,
	
	/**
	 * Edit table properties
	 * @param {Number} tabToOpen The index of the tab to make active.
	 */
	edit: function (tabToOpen)
	{
		this._createBoxIfRequired();
		
		this._box.show();
		this._tabpanel.setActiveTab(tabToOpen || 0);
		
		this._fillBox();
	},
	
	/**
	 * Edit table general properties
	 * @param {Ametys.ribbon.element.ui.ButtonController}  controller The controller calling this function
	 */
	editGeneral: function (controller) 
	{ 
		this.edit(0); 
	},
	
	/**
	 * Edit table layout properties
	 * @param {Ametys.ribbon.element.ui.ButtonController}  controller The controller calling this function
	 */
	editLayout: function (controller) 
	{ 
		this.edit(0); 
	},
	
	/**
	 * Edit table size properties
	 * @param {Ametys.ribbon.element.ui.ButtonController}  controller The controller calling this function
	 */
	editSize: function(controller) 
	{ 
		this.edit(1); 
	},
	
	/**
	 * Update the dialog box input fields
	 * @private
	 */
	_fillBox: function ()
	{
		var tableNode = Ametys.plugins.cms.editor.Tables._currentTable;
		
		Ext.getCmp('tablepropertiescaption').setValue(Ametys.plugins.cms.editor.Tables._getCaption(tableNode));
		Ext.getCmp('tablepropertiessummary').setValue(Ametys.plugins.cms.editor.Tables._getSummary(tableNode));

		// FIXME "tinyMCE.activeEditor" a better method is to use the field.getEditor()
		if (tinyMCE.activeEditor.dom.hasClass(tableNode, 'floatleft'))
		{
			Ext.getCmp('tablepropertiesfloatleft').setValue(true);
		}
		else if (tinyMCE.activeEditor.dom.hasClass(tableNode, 'floatright'))
		{
			Ext.getCmp('tablepropertiesfloatright').setValue(true);
		}
		else
		{
			Ext.getCmp('tablepropertiesnofloat').setValue(true);
		}
		
		// remove existing columns
		var columnsize = Ext.getCmp('tablecolumnssize');
		while (columnsize.items.length > 0)
		{
			columnsize.remove(columnsize.items.get(0))
		}
		// adding required columns
		var cols = Ametys.plugins.cms.editor.Tables._countCells(tableNode);
		for (var i = 0; i < cols; i++)
		{
		    var input = new Ext.form.field.Number ({
		    	allowDecimals: false,
				fieldLabel : "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_COLS_ELT_SIZE_COL}}" + (i+1),
				labelAlign: 'top',
				labelSeparator: '',
		    	name: 'cols',
		    	id: 'tablecolumnssizecol' + (i+1),
		    	emptyText: "{{i18n CONTENT_EDITION_TABLE_COLUMN_WIDTH_EMPTYTEXT}}",
		    	minValue: 1,
				allowBlank: true,
				width: 50
			});
		    columnsize.add(input)
		}

		// remove existing lines
		var linesize = Ext.getCmp('tablelinessize');
		while (linesize.items.length > 0)
		{
			linesize.remove(linesize.items.get(0))
		}
		// adding required columns
		var lines = tableNode.rows.length
		for (var i = 0; i < lines; i++)
		{
		    var input = new Ext.form.field.Number ({
		    	allowDecimals: false,
		    	labelAlign: 'top',
		    	labelSeparator: '',
				fieldLabel : "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_LINES_ELT_SIZE_COL}}" + (i+1),
			    name: 'lines',
			    id: 'tablelinessizeline' + (i+1),
			    emptyText: "{{i18n CONTENT_EDITION_TABLE_ROW_HEIGHT_EMPTYTEXT}}",
			    minValue: 1,
				allowBlank: true,
				width: 50
			});
		    linesize.add(input)
		}

		this._fillBox2();
	},
	
	/**
	 * Update columns and lines size inputs
	 * @private
	 */
	_fillBox2: function()
	{
		var tableNode = Ametys.plugins.cms.editor.Tables._currentTable;
		var disabledState = tableNode.style.width == '100%';
		Ext.getCmp('tablepropertiesfloatleft').setDisabled(disabledState);
		Ext.getCmp('tablepropertiesnofloat').setDisabled(disabledState);
		Ext.getCmp('tablepropertiesfloatright').setDisabled(disabledState);

		var columnsize = Ext.getCmp('tablecolumnssize');
		
		// filling cols width
		var grid = Ametys.plugins.cms.editor.Tables._getTableGrid(tableNode);
		for (var index = 0; index < grid[0].length; index++)
		{
			var width = Ametys.plugins.cms.editor.Tables._getColWantedWidthByIndex(index, grid);
			columnsize.items.get(index).setValue(width);
		}

		// filling lines height
		var linesize = Ext.getCmp('tablelinessize');
		for (var index = 0; index < grid.length; index++)
		{
			var height = Ametys.plugins.cms.editor.Tables._getRowWantedHeightByIndex(index, grid);
			linesize.items.get(index).setValue(height);
		}
	},
	
	/**
	 * Creates the dialog box properties #_box if needed
	 * @private
	 */
	_createBoxIfRequired: function()
	{
		if (this._box != null)
		{
			return;
		}
		
		this._tabpanel = Ext.create ('Ext.TabPanel', {
	    	activeItem: 0,
	    	padding: 2,
	    	cls: 'table-properties',
			items: [
			    new Ext.Panel({
					title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_TABLE}}",
					layout: 'form',
					border: true,
					padding: 10,
					items: [
						    {
						    	xtype: 'fieldset',
						        title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_TABLE_ELT_PROPERTIES}}",
						        collapsible: false,
						        autoHeight: true,
								labelWidth: 150,
						        items: [
									    {
									    	xtype: 'textfield',
											fieldLabel : "{{i18n CONTENT_EDITION_TABLE_CAPTION_LABEL}}",
											ametysDescription: "{{i18n CONTENT_EDITION_TABLE_CAPTION_DESCRIPTION}}",
							     	    	name: 'caption',
							     	    	id: 'tablepropertiescaption',
							     	    	width: 300
										},
									    {
											xtype: 'textfield',
											fieldLabel : "{{i18n CONTENT_EDITION_TABLE_SUMMARY_LABEL}}",
											ametysDescription: "{{i18n CONTENT_EDITION_TABLE_SUMMARY_DESCRIPTION}}",
							     	    	name: 'summary',
							     	    	id: 'tablepropertiessummary',
							     	    	width: 300
										}
										
						        ]
						    },
						    {
						    	xtype: 'fieldset',
						        title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_TABLE_ELT_DRESS}}",
						        collapsible: false,
						        autoHeight: true,
								labelWidth: 150,
			                	id: 'tablepropertiesfloatfieldset',
						        items: [
										{
											xtype: 'component',
											cls: 'a-text',
											html: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_TABLE_ELT_DRESS_DISABLED}}"
										},
						                {
						                	xtype: 'radiofield',
						                	hideLabel: true,
						                	boxLabel: "{{i18n CONTENT_EDITION_TABLE_FLOAT_LEFT_LABEL}}",
						                	ametysDescription: "{{i18n CONTENT_EDITION_TABLE_FLOAT_LEFT_DESCRIPTION}}",
						                	name: 'float',
						                	id: 'tablepropertiesfloatleft'
						                },
						                {
											xtype: 'radiofield',
						                	hideLabel: true,
						                	boxLabel: "{{i18n CONTENT_EDITION_TABLE_NO_FLOAT_LABEL}}",
						                	ametysDescription: "{{i18n CONTENT_EDITION_TABLE_NO_FLOAT_DESCRIPTION}}",
						                	name: 'float',
						                	id: 'tablepropertiesnofloat'
						                },
						                {
						                	xtype: 'radiofield',
						                	hideLabel: true,
						                	boxLabel: "{{i18n CONTENT_EDITION_TABLE_FLOAT_RIGHT_LABEL}}",
						                	ametysDescription: "{{i18n CONTENT_EDITION_TABLE_FLOAT_RIGHT_DESCRIPTION}}",
						                	name: 'float',
						                	id: 'tablepropertiesfloatright'
						                }
						        ]
						    }
					]
				}),
			    new Ext.Panel({
					title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_COLS}}",
					border: true,
					scrollable: true,
					padding: 10,
					items: [
					   {
					    	xtype: 'fieldset',
					        title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_COLS_ELT_ADJUST}}",
					        collapsible: false,
					        autoHeight: true,
							labelWidth: 150,
		                	id: 'tablecolumnsadjust',
					        items: [
									{
										xtype: 'component',
										cls: 'a-text',
										width: 500,
										html: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_COLS_ELT_ADJUST_WARN}}"
									},
					                {
					                	xtype: 'button',
					                	text: "{{i18n CONTENT_EDITION_TABLE_COLSIZE_AJUST_TO_CONTENT_LABEL}}",
					                	icon: Ametys.getPluginResourcesPrefix('cms') + "/img/content/edition/table/Column_Size_Ajust_Content_16.png",
					                	handler: Ext.bind(this._colSizeAjustToContent, this),
					                	scale: 'small',
					                	cls: 'adjust',
					                	name: 'adjusttocontent',
					                	width: 160
					                },
									{
										xtype: 'component',
										cls: 'a-text',
										width: 300,
										style: { 'marginLeft': '15px', 'float': 'left' },
										html: "{{i18n CONTENT_EDITION_TABLE_COLSIZE_AJUST_TO_CONTENT_DESCRIPTION}}"
									},
					                {
					                	xtype: 'button',
					                	text: "{{i18n CONTENT_EDITION_TABLE_COLSIZE_AJUST_TO_WINDOW_LABEL}}",
					                	icon: Ametys.getPluginResourcesPrefix('cms') + "/img/content/edition/table/Column_Size_Ajust_Window_16.png",
					                	handler: Ext.bind(this._colSizeAjustToWindow, this),
					                	scale: 'small',
					                	cls: 'adjust',
					                	name: 'adjusttowindow',
					                	width: 160
					                },
									{
										xtype: 'component',
										cls: 'a-text',
										width: 300,
										style: { 'marginLeft': '15px', 'float': 'left' },
										html: "{{i18n CONTENT_EDITION_TABLE_COLSIZE_AJUST_TO_WINDOW_DESCRIPTION}}"
									},
					                {
										xtype: 'button',
					                	text: "{{i18n CONTENT_EDITION_TABLE_COLSIZE_FIXE_LABEL}}",
					                	icon: Ametys.getPluginResourcesPrefix('cms') + "/img/content/edition/table/Column_Size_Fixed_16.png",
					                	handler: Ext.bind(this._colSizeFixed, this),
					                	scale: 'small',
					                	cls: 'adjust',
					                	name: 'noadjust',
					                	width: 160
					                },
									{
										xtype: 'component',
										cls: 'a-text',
										width: 300,
										style: { 'marginLeft': '15px', 'float': 'left' },
										html: "{{i18n CONTENT_EDITION_TABLE_COLSIZE_FIXE_DESCRIPTION}}"
									}
					        ]
					    },
					    {
					    	xtype: 'fieldset',
					        title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_COLS_ELT_SIZE}}",
					        collapsible: false,
					        cls: 'size',
					        autoHeight: true,
					        items: [
									{
										xtype: 'component',
										cls: 'a-text',
										html: "{{i18n CONTENT_EDITION_TABLE_COLUMN_WIDTH_DESCRIPTION}}",
										colspan: 8
									},
									{
										xtype: 'panel',
										border: false,
										id: 'tablecolumnssize',
										layout: {
								        	type: 'table',
								        	columns: 8,
								        	tdAttrs: {
								        		width: '71px'
								        	}
								        }
										// Dynamic inputs here
									}
									
							]
					    }
				    ]
				}),
			    new Ext.Panel({
					title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_LINES}}",
					border: true,
					padding: 10,
					items: [
						    {
						    	xtype: 'fieldset',
						        title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_TAB_LINES_ELT_SIZE}}",
						        collapsible: false,
						        cls: 'size',
						        autoHeight: true,
						        items: [
										{
											xtype: 'component',
											cls: 'a-text',
											html: "{{i18n CONTENT_EDITION_TABLE_ROW_HEIGHT_DESCRIPTION}}"
										},
										{
											xtype: 'panel',
											border: false,
											id: 'tablelinessize',
											layout: {
									        	type: 'table',
									        	columns: 8,
									        	tdAttrs: {
									        		width: '71px'
									        	}
									        }
											// Dynamic inputs here
										}
								]
						    }
					    ]
			    })
			]
	    });
		
		this._box = Ext.create ('Ametys.window.DialogBox', {
			title: "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_LABEL}}",
			icon: Ametys.getPluginResourcesPrefix("cms") + "/img/content/edition/table/insert_16.png",
			
			width: 640,
			height: 460,
			scrollable: false,
			cls: 'ametys-dialogbox',
			border: false,
			
			layout: 'fit',
			
			items: [ this._tabpanel ],

			closeAction: 'hide',
			defaultFocus: 'tablepropertiescaption',
			
			referenceHolder: true,
			defaultButton: 'save',
			defaultButtonTarget: 'el',
			
			buttons : [{
				reference: 'save',
				text : "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_OK}}",
				handler : Ext.bind(this._saveProperties, this)
			},{
				text : "{{i18n CONTENT_EDITION_TABLE_PROPERTIES_CANCEL}}",
				handler : function() { this._box.hide(); tinyMCE.activeEditor.focus(); },
				scope: this
			}]
		});
	},
	
	/**
	 * Function called after 'Ok' button of properties dialog box is pressed
	 * Save the table properties
	 * @private
	 */
	_saveProperties: function()
	{
		var tableNode = Ametys.plugins.cms.editor.Tables._currentTable;

		// FIXME "tinyMCE.activeEditor" a better method is to use the field.getEditor()
		tinyMCE.activeEditor.focus();
		tinyMCE.activeEditor.execCommand('mceBeginUndoLevel');

		Ametys.plugins.cms.editor.Tables.setCaption(Ext.getCmp('tablepropertiescaption').getValue());
		Ametys.plugins.cms.editor.Tables.setSummary(Ext.getCmp('tablepropertiessummary').getValue());
		
		if (!Ext.getCmp('tablepropertiesfloatleft').disabled && Ext.getCmp('tablepropertiesfloatleft').getValue() == true)
		{
			Ametys.plugins.cms.editor.Tables._applyFloatLeft(Ametys.plugins.cms.editor.Tables._currentTable);
		}
		else if (!Ext.getCmp('tablepropertiesfloatright').disabled && Ext.getCmp('tablepropertiesfloatright').getValue() == true)
		{
			Ametys.plugins.cms.editor.Tables._applyFloatRight(Ametys.plugins.cms.editor.Tables._currentTable);
		}
		else
		{
			Ametys.plugins.cms.editor.Tables._applyNoFloat(Ametys.plugins.cms.editor.Tables._currentTable);
		}
		
		var grid = Ametys.plugins.cms.editor.Tables._getTableGrid(tableNode);
		
		var columnsize = Ext.getCmp('tablecolumnssize');
		for  (var index = 0; index < grid[0].length; index++)
		{
			var width = columnsize.items.get(index).getValue();
			Ametys.plugins.cms.editor.Tables._setColWidthByIndex(index, width != '' ? width + 'px' : '', grid)
		}
		
		var linesize = Ext.getCmp('tablelinessize');
		for  (var index = 0; index < grid.length; index++)
		{
			var height = linesize.items.get(index).getValue();
			Ametys.plugins.cms.editor.Tables._setRowHeightByIndex(index, height != '' ? height + 'px' : '', grid)
		}
		
		tinyMCE.activeEditor.execCommand('mceEndUndoLevel');
		
		this._box.hide();
		tinyMCE.activeEditor.focus();
	},
	
	/**
	 * Call {@link Ametys.plugins.cms.editor.Tables#colSizeAjustToContent} function and update columns and lines size inputs
	 * @param {Ext.Button} btn The button calling the function
	 * @private
	 */
	_colSizeAjustToContent: function (btn) 
	{
		Ametys.plugins.cms.editor.Tables.colSizeAjustToContent();
		this._fillBox2();
		btn.focus();
	},
	
	/**
	 * Call {@link Ametys.plugins.cms.editor.Tables#colSizeAjustToWindow} function and update columns and lines size inputs
	 * @param {Ext.Button} btn The button calling the function
	 * @private
	 */
	_colSizeAjustToWindow: function (btn) 
	{
		Ametys.plugins.cms.editor.Tables.colSizeAjustToWindow();
		this._fillBox2();
		btn.focus();
	},
	
	/**
	 * Call {@link Ametys.plugins.cms.editor.Tables#colSizeFixed} function and update columns and lines size inputs
	 * @param {Ext.Button} btn The button calling the function
	 * @private
	 */
	_colSizeFixed: function (btn) 
	{
		Ametys.plugins.cms.editor.Tables.colSizeFixed();
		this._fillBox2();
		btn.focus();
	}
});