/*
 *  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 download the InDesign model.
 * @private
 */
Ext.define('Ametys.plugins.odf.web.export.DownloadIndt', {
    singleton: true,
    
    /**
     * @private
     * @property {Ametys.window.DialogBox} _box The dialog box choosing the model .indt
     */
     
    /**
     * @private
     * @property {Ext.form.Panel} _formPanel The form panel of the dialog box.
     */
    
    /**
     * @private
     * @property {Boolean} _initialized Indicates if the dialog box is initialized.
     */
    
    /**
     * Open dialog box to choose the .indt file
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    act: function (controller)
    {
        this._delayedInitialize();
        this._box.show();
        this._initForm();
    },
    
    /**
     * @private
     * Creates the dialog box
     */
    _delayedInitialize: function ()
    {
        if (!this._initialized)
        {
            this._formPanel = this._createFormPanel();
            
            this._box = Ext.create('Ametys.window.DialogBox', {
                title: "{{i18n PLUGINS_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_TITLE}}",
                icon: Ametys.getPluginResourcesPrefix('odf') + '/img/actions/export_indesign_16.png',
                
                width: 520,
                scrollable: false,
                
                items: [this._formPanel],
                
                defaultFocus: 'title',
                closeAction: 'hide',
                buttons: [{
                    text: "{{i18n PLUGINS_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_OK}}",
                    itemId: 'ok-btn',
                    disabled: true,
                    handler: Ext.bind(this._validate, this)
                }, {
                    text: "{{i18n PLUGINS_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_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_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_HINT1}}",
                    cls: 'a-text'
                },
                {
                    xtype: 'combo',
                    name: 'templateName',
                    itemId: 'templateName',
                    fieldLabel: "{{i18n PLUGINS_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_COMBOBOX_FIELD_LABEL}}",
                    emptyText: "{{i18n PLUGINS_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_COMBOBOX_EMPTY_TEXT}}",
            
                    store: {
                        fields: [
                            {name: 'value', mapping: 'filepath'},
                            {name: 'displayText', mapping: 'filename', type: 'string'}
                        ],
                        sorters: {property: 'displayText', direction:'ASC'},
                        proxy: {
                            type: 'ametys',
                            plugin: 'odf-web',
                            url: 'indesign/templates.json',
                            reader: {
                                type: 'json',
                                rootProperty: 'templates'
                            }
                        },
                        autoLoad: true,
                        listeners: {
                            'beforeload': Ext.bind(this._onBeforeLoad, this)
                        }
                    },
                    valueField: 'value',
                    displayField: 'displayText',
                    
                    queryMode: 'local',
                    allowBlank: false,
                    forceSelection : true,
                    triggerAction: 'all',
                    
                    listeners: {
                        'select': Ext.bind(this._onSelectFile, this)
                    }
                },
                {
                    xtype: 'container',
                    html: "{{i18n PLUGINS_ODFWEB_EXPORT_INDESIGN_DOWNLOAD_INDT_DIALOG_HINT2}}",
                    cls: 'a-text-light'
                }
                
            ]
        });
        
        return formPanel;
    },
    
    /**
     * Function called before loading the store
     * @param {Ext.data.Store} store The store
     * @param {Ext.data.operation.Operation} operation The object that will be passed to the Proxy to load the store
     * @private
     */
    _onBeforeLoad:function(store, operation)
    {
        operation.setParams( Ext.apply(operation.getParams() || {}, {
            skinName: Ametys.getAppParameter('skin')
        }));
    },
    
    /**
     * Listener on file selection
     * @param {Ext.form.field.ComboBox} combo The combo box
     * @param {Ext.data.Model} record The selected record
     */
    _onSelectFile: function(combo, record)
    {
         this._box.down('#ok-btn').setDisabled(!combo.getValue());
    },
    
    /**
     * @private
     * Initializes the form with some optional values.
     */
    _initForm: function ()
    {
        var form = this._formPanel.getForm();
        form.reset();
        
        this._box.down('#ok-btn').setDisabled(true);
    },
    
    /**
     * @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();
        Ametys.openWindow(Ametys.getPluginDirectPrefix('odf-web') + '/indesign/download/' + Ametys.getAppParameter('skin') + '/' + values.templateName);
        
        this._box.close();
    }
    
});