/*
 *  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 class provides a widget to select a folder in the resource explorer tree.
 * See {@link Ametys.cms.uihelper.ChooseResource}<br>
 * 
 * This widget is registered for fields of type Ametys.form.WidgetManager#TYPE_STRING.
 */
Ext.define('Ametys.cms.form.widget.ExplorerFolder', {
    extend : 'Ametys.form.AbstractField',
        
    canDisplayComparisons: true,
   
    /**
     * @cfg {String} chooseResourceWindowTitle Title of the dialog box to choose resources. See {@link Ametys.cms.uihelper.ChooseResource#open}.
     */
    chooseResourceWindowTitle: "{{i18n PLUGINS_CMS_WIDGET_FOLDER_PICKER_SELECT_RESOURCES_FOLDER}}",
    /**
     * @cfg {String} chooseResourceWindowIcon The full icon path the dialog box to choose resources. See {@link Ametys.cms.uihelper.ChooseResource#open}. 
     */
    chooseResourceWindowIconCls: 'ametysicon-file98',
    /**
     * @cfg {String} chooseResourceHelpMessage The help message to display on top of dialog box to choose resources. See {@link Ametys.cms.uihelper.ChooseResource#open}. 
     */
    chooseResourceHelpMessage: "{{i18n PLUGINS_CMS_WIDGET_FOLDER_PICKER_SELECT_RESOURCES_FOLDER_HINT}}",

    /**
     * @cfg {String} buttonIcon The full path to the button icon (in 16x16 pixels)
     */
    buttonIconCls: 'ametysicon-file98',
    /**
     * @cfg {String} buttonTooltipText The button tooltip text
     */ 
    buttonTooltipText : "{{i18n PLUGINS_CMS_WIDGET_FOLDER_PICKER_SELECT_RESOURCES_FOLDER}}",
    /**
     * @cfg {String} deleteButtonIcon The full path to the delete button icon (in 16x16 pixels)
     */
    deleteButtonIconCls: 'ametysicon-delete30', 
    /**
     * @cfg {String} deleteTooltipText The delete button tooltip text
     */ 
    deleteTooltipText : "{{i18n PLUGINS_CMS_WIDGET_FOLDER_PICKER_DELETE_FOLDER_BUTTON}}",
    /**
     * @cfg {String} emptyText The text for empty field
     */
    emptyText: "{{i18n PLUGINS_CMS_WIDGET_FOLDER_PICKER_NO_FOLDER_SELECTED}}",
    
    /**
     * @cfg {Number} buttonOffset The number of pixels of space reserved between
     *      the button and the text field (defaults to 5). 
     */
    buttonOffset: 5,
    /**
     * @cfg {Number} width The text field width in pixel(defaults to 470)
     */
    width: 470,
    
    xtype: 'edition.explorer-folder',
    
    /**
     * @inheritdoc
     * Initializes the widget field and button
     */
    initComponent : function() 
    {
        var me = this;
                
        var explorerFolderConfig = Ext.applyIf(this.explorerFolderConfig || {}, {
        	cls: Ametys.form.AbstractField.READABLE_TEXT_CLS,
            html: this.emptyText,
            flex: 1
        });
        this.explorerFolderField = Ext.create('Ext.Component', explorerFolderConfig);

        // Button to open the dialog box for choosing the folder
        var chooseResourcePopupConfig = Ext.applyIf(this.chooseResourcePopupConfig || {}, {
            iconCls: this.buttonIconCls,
            tooltip: this.buttonTooltipText,
            handler: this._showChooseResourcePopup,
            scope: this
        });
        this._chooseResourcePopupButton = Ext.create('Ext.button.Button', chooseResourcePopupConfig);
        
        // Button which deletes the value.
        var deleteButtonConfig = Ext.applyIf(this.deleteButtonConfig || {}, {
            iconCls: this.deleteButtonIconCls,
            tooltip: this.deleteTooltipText,
            handler: this._deleteValue,
            scope: this,
            hidden: true
        });
        this._deleteButton = Ext.create('Ext.button.Button', deleteButtonConfig);
      
        this.items = [this.explorerFolderField, this._chooseResourcePopupButton, this._deleteButton];

        this.layout = 'hbox';
        this.cls = [this.emptyCls, 'ametys-explorerfolder-field'];
        
        this.callParent(arguments);
    },  
    
    /**
     * Delete the current widget value
     * @private
     */
     _deleteValue: function()
     {
         this.setValue(null);
         this._updateUI();
     },
    
    /**
     * @inheritdoc
     */
    afterRender: function()
    {
        this.callParent(arguments);
        this._updateUI();
    },
    
    /**
     * Update UI
     * @private
     */
    _updateUI: function()
    {   
        var value = this.value;
        
        if (!this.rendered)
        {
            return;
        }
        
        if (!value) 
        {
            this._deleteButton.hide();
            this._chooseResourcePopupButton.setVisible(!this.readOnly);
        }
        else
        {
            this._deleteButton.setVisible(!this.readOnly);
            this._chooseResourcePopupButton.hide();
        }
        
        this._updateDisplayField();
    },    

    /**
     * Update the display field as a understanding value for the end user
     * @private
     */
    _updateDisplayField: function()
    {
        if (!this.rendered)
        {
            return;
        }
        
        if (this.value)
        {
            Ametys.explorer.ExplorerNodeDAO.getExplorerNode(this.value, Ext.bind(this._updateDisplayFieldCb, this));
        }
        else
        {
            this._updateDisplayFieldCb(null);
        }
    },

    /**
     * transform the widget value in a human readable string
     * @return {String} a human readable string
     */
    getReadableValue: function ()
    {
        if (this.value)
        {
            return this._readableValue || this.value;
        }
        else
        {
            return this.emptyText;
        }
    },
    
    /**
     * @inheritdoc
     * Sets a data value into the field and updates the display field
     * @param {Object} value The value to set.
     */
    setValue: function (value) 
    {   
        this.callParent(arguments);
        this._updateUI();
    },
    
    /**
     * @private
     * The launcher for the choose resource popup window.
     */
    _showChooseResourcePopup : function() 
    {
        Ametys.cms.uihelper.ChooseResource.open({
            title: this.chooseResourceWindowTitle,
            iconCls: this.chooseResourceWindowIconCls,
            helpmessage: this.chooseResourceHelpMessage,
            currentId: this.getValue(),
            ignoreFiles: true,
            folderSelectable: true,
            callback:  Ext.bind(this._showChooseResourcePopupCb, this)
        });
    },
 
    /**
     * Callback function called after choosing the folder.
     * Update the field value.
     * @param {String} id The selected folder id
     * @private
    */
    _showChooseResourcePopupCb: function(id)
    {
        this.setValue(id);
    },
    
    /**
     * Set the readable value from the selected folder
     * @param {Ametys.explorer.ExplorerNode} node The explorer node (folder)
     * @private
     */
    _updateDisplayFieldCb: function(node)
    {
        if (node)
        {
            var name = node.getName();
            if (name == 'ametys-internal:resources')
            {
                this._readableValue = "{{i18n plugin.explorer:PLUGINS_EXPLORER_ROOT_NODE}}";
            }
            else
            {
                this._readableValue = name;
            }
            this.removeCls(this.emptyCls);
        }
        else
        {
            this.addCls(this.emptyCls);
        }
        
        this.explorerFolderField.update("<span>" + this.getReadableValue() + "</span>");
    },
    
    setComparisonValue: function(otherValue, base)
    {
        this.toggleCls("ametys-explorerfolder-comparable", true);
    }
});