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

/**
 * Singleton class to export a program to InDesign format.
 * @private
 */
Ext.define('Ametys.plugins.odf.indesign.ExportInDesign', {
	singleton: true,
	
	/**
 	 * @private
 	 * @property {Ametys.window.DialogBox} _box The dialog box for creating/editing a catalog.
 	 */
 	 
 	/**
 	 * @private
 	 * @property {Ext.form.Panel} _formPanel The form panel of the dialog box.
 	 */
 	
 	/**
	 * @private
	 * @property {Boolean} _initialized Indicates if the create/edit dialog box is initialized.
	 */
	
	/**
	 * Exports a program in InDesign format.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	act: function (controller)
	{
		var target = controller.getMatchingTargets()[0];
 		var programId = target.getParameters().id;
		
		this.open(programId, this._doExport);
	},
	
    /**
     * Open the dialog box to prepare InDesign export
     * @param {String} programId The id of content to export
     * @param {Function} callback The callback function responsible for effective export
     * @param {Object} callback.values The chosen export parameters
     * @param {String} callback.values.id The id of program to export
     * @param {String} callback.values.xslt The XSLT file for unit export
     */
    open: function (programId, callback)
    {
        this._cbFn = callback;
        
        this._delayedInitialize();
        this._box.show();
        this._initForm(programId);
    },
    
    /**
     * @private
     * Do export
     * @param {Object} values The selected values :
     * @param {String} values.id The id of program to export
     * @param {String} values.xslt The XSLT file for unit export
     */
    _doExport: function (values)
    {
        values.userLocale = Ametys.getAppParameter('user').locale;
        Ametys.openWindow(Ametys.getPluginDirectPrefix('odf') + '/indesign/program.xml', values);
    },
    
	/**
	 * @private
	 * Creates the dialog box
	 */
	_delayedInitialize: function ()
	{
		if (!this._initialized)
		{
			this._formPanel = this._createFormPanel();
			
			this._box = Ext.create('Ametys.window.DialogBox', {
				title: "{{i18n PLUGINS_ODF_EXPORT_INDESIGN_DIALOGBOX_TITLE}}",
	            icon: Ametys.getPluginResourcesPrefix('odf') + '/img/actions/export_indesign_16.png',
	            
	            width: 450,
		        scrollable: false,
	            
	            items: [this._formPanel],
	            
	            defaultFocus: 'title',
	            closeAction: 'hide',
	            buttons: [{
	                text: "{{i18n PLUGINS_ODF_EXPORT_INDESIGN_DIALOGBOX_OK}}",
	                handler: Ext.bind(this._validate, this)
	            }, {
	                text: "{{i18n PLUGINS_ODF_EXPORT_INDESIGN_DIALOGBOX_CANCEL}}",
	                handler: Ext.bind( function() {this._box.close();}, this)
	            }]    
			});
			
			this._initialized = true;
		}
	},
	
	/**
 	 * Creates the form panel of this dialog box.
 	 * @return {Ext.form.Panel} The form panel
 	 * @private
 	 */
 	_createFormPanel: function()
 	{
		var formPanel = Ext.create('Ext.form.Panel', {
	        defaultType: 'combo',
	        defaults: {
	        	cls: 'ametys',
	        	labelSeparator: '',
	        	labelAlign: 'right',
	        	labelWidth: 80,
	        	width: '100%',
	        	msgTarget: 'side'
	        },
	        
	        border: false,
	        scrollable: true,
	        cls: 'text-dialog',
	        
	        items: [
		        {
		        	xtype: 'hidden',
		        	name: 'id'
		        },
		        {
		        	xtype: 'container',
		        	itemId: 'hint',
		        	html: "{{i18n PLUGINS_ODF_EXPORT_INDESIGN_DIALOGBOX_HINT}}",
		        	cls: 'a-text'
		        },
		        {
		        	xtype: 'combo',
		        	name: 'xslt',
		        	itemId: 'xslt',
		        	fieldLabel: "{{i18n PLUGINS_ODF_EXPORT_INDESIGN_DIALOGBOX_XSLT}}",
	                
	                store: {
	                	fields: [
				        	{name: 'value', mapping: 'name'},
				        	{name: 'displayText', mapping: 'label', type: 'string'}
				    	],
				    	sorters: {property: 'displayText', direction:'ASC'},
				    	proxy: {
				    		type: 'ametys',
				    		plugin: 'odf',
							url: 'indesign/get-xslt.json',
				    		reader: {
				    			type: 'json',
				    			rootProperty: 'files'
				    		}
				    	},
				    	autoLoad: true,
				    	listeners: {
				    		'load': Ext.bind(this._onLoadXslt, this)
				    	}
	                },
	                valueField: 'value',
	                displayField: 'displayText',
	                
	                queryMode: 'local',
	                allowBlank: false,
	                forceSelection : true,
	                triggerAction: 'all'
		        },
		        {
		        	xtype: 'container',
		        	itemId: 'noXslt',
		        	html: "{{i18n PLUGINS_ODF_EXPORT_INDESIGN_DIALOGBOX_NO_XSLT}}",
		        	hidden: true,
		        	cls: 'a-text-warning'
		        }
		        
	        ]
 		});
 		
 		return formPanel;
 	},
 	
 	/**
 	 * @private
 	 * Listener on load of record
 	 * @param {Ext.data.Store} store The store
 	 * @param {Ext.data.Model[]} records The records
 	 */
 	_onLoadXslt: function(store, records)
 	{
 		var formPanel = this._formPanel;
 		
 		if (records.length == 0)
		{
			this._formPanel.items.get('noXslt').show();
		}
		else
		{
			this._formPanel.items.get('noXslt').hide();
			this._formPanel.getForm().findField('xslt').setValue(records[0]);
		}
 	},
 	
 	/**
 	 * @private
 	 * Initializes the form with some optional values.
 	 * @param {String} programId The program id
 	 */
	_initForm: function (programId)
 	{
 		var form = this._formPanel.getForm();
 		
		form.reset();
 		form.findField('id').setValue(programId);
 	},
 	
 	/**
 	 * @private
 	 * Handler for the 'ok' button of the dialog box
 	 */ 
    _validate: function ()
    {
        var form = this._formPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        var values = form.getValues();
 		
        if (Ext.isFunction(this._cbFn))
        {
            this._cbFn(values);
        }
        
        this._box.close();
    }
	
});