/*

 *  Copyright 2014 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 displays thesaurus
 * @private
 */
Ext.define('Ametys.plugins.thesaurus.tool.ThesaurusTool', {
	extend: "Ametys.plugins.cms.content.tool.HierarchicalReferenceTablesTool",
	
	/**
	 * @property {String} _thesaurusId The id of thesaurus
	 * @private
	 */
	
	/**
	 * @property {String} _thesaurusLabel The label of thesaurus
	 * @private
	 */
	
	sendCurrentSelection: function()
	{
		var selection = this._tree.getSelection();
        
        var targets = this._getMessageTargetCfg(selection);
        
		var mtTargets = [];
		if (!Ext.isEmpty(this.getMicrothesaurusId()))
		{
			mtTargets.push({
			    id: Ametys.message.MessageTarget.MICROTHESAURUS,  	      	  
				parameters: {
					id: this.getMicrothesaurusId(),
                    thesaurusId: this._thesaurusId,
					label: this._tree.getRootNode().get('title')
				},
				subtargets: targets
      	  	});
		}
		
		Ext.create("Ametys.message.Message", {
  	        type: Ametys.message.Message.SELECTION_CHANGED,
  	        targets: {
  	          id: Ametys.message.MessageTarget.THESAURUS,  	      	  
  	      	  parameters: {
  	      		  id: this._thesaurusId,
  	      		  label: this._thesaurusLabel,
  	      		  contentType: this.getMicrothesaurusId()
  	      	  },
  	      	  subtargets: mtTargets
   			}
    	});   	
	},
	
	setParams: function (params)
	{
        this.showRefreshing();
        
		this._thesaurusId = params['id'];
        
        Ametys.plugins.thesaurus.ThesaurusDAO.getMicrothesaurii([this._thesaurusId], function(microthesaurii) {
            if (microthesaurii && microthesaurii.length > 0)
            {
                // Initialize with first microthesaurii
                params.contentType = microthesaurii[0];
                Ametys.plugins.thesaurus.tool.ThesaurusTool.superclass.setParams.call(this, params);
            }
            else
            {
                // No microthesaurus yet
                Ametys.plugins.cms.content.tool.HierarchicalReferenceTablesTool.superclass.setParams.call(this, params);
                this._updateInfos();
                var me = this;
                this._tree.loadMicrothesaurii(null, function () {
                    me.showUpToDate();
                    me.showRefreshed();
                });
            }
            
        }, {scope: this});
	},
    
    _getReferenceTablePropertiesCb: function(result, params)
    {
        this.callParent(arguments);
        this._updateInfos();
        
        this._tree.loadMicrothesaurii(this.getParams().contentType);
    },
    
    /**
     * Update tool's information
     * @private
     */
    _updateInfos: function()
    {
        Ametys.plugins.thesaurus.ThesaurusDAO.getThesaurusLabel([this._thesaurusId], function(label) {
            this.setTitle(label);
            this.setGlyphIcon("ametysicon-books")
            this._thesaurusLabel = label;
        }, {scope: this});
    },
	
	createPanel: function()
	{
		var i = this.getId().indexOf('$') + 1;
		var thesaurusId = this.getId().substring(i);
		var plugins = {
                ptype: 'cellediting',
                clicksToEdit: 1,
                editAfterSelect: true,
                listeners: {
                    'beforeedit': this._onBeforeEdit,
                    'edit': this._onEdit,
                    scope: this
                }
            };
		
		this._tree = Ext.create('Ametys.plugins.thesaurus.tool.ThesaurusTreePanel', {
			 thesaurusId: thesaurusId,
			 tool: this,
			 rootVisible: true,
			 rootCfg: {
				 expanded: false,
		            text: ""
			 },
			 listeners: {
	                'selectionchange': this.sendCurrentSelection,
	                'itemdblclick': this._onItemDoubleClick,
	                scope: this
	            },
			 plugins: plugins,
			 columns: [{
	                xtype: 'treecolumn',
	                dataIndex: 'text',
	                flex: 1,
	                editor: {
	                    xtype: 'textfield',
	                    allowBlank: false,
	                    selectOnFocus: true
	                }
	            }],
			 viewConfig: {
	            plugins: {
	                ptype: 'ametystreeviewdragdrop',
	                containerScroll: true,
	                appendOnly: true,
	                sortOnDrop: true,
	                expandDelay: 500,
	                setAmetysDragInfos: Ext.bind(this._getDragInfo, this),
                    setAmetysDropZoneInfos: Ext.bind(this._getDropInfo, this)
	                }
	            }
		 });
		 
		this._tree.getMTComboBox().on('change', this._onMicrothesaurusChange, this);
		
		 return this._tree;
	},
	
	refresh: function()
	{	
        // Do not reload tool infos and microthesaurii if the refresh comes from a tree modification
        var fullRefresh = this._lastOutOfDateNodes.length == 0;
        
        this.callParent();
        
        if (fullRefresh) 
        {
            // Update tool info
	        this._updateInfos();
			
	        // Load microthesaurus combox box
	        this._tree.loadMicrothesaurii(this.getParams().contentType);
        }
	},
	
	/**
	 * Get the thesaurus id
	 * @return {String} the microthesaurus id
	 */
	getMicrothesaurusId: function() 
	{
		return this._tree.getMTComboBox().getValue();
	},
	
	/**
	 * Listener when a Ametys.message.Message#DELETED message was received
	 * @param {Ametys.message.Message} message The modified message
	 * @private
	 */
	_onMessageDeleted: function (message)
	{
		this.callParent(arguments);
		
		var target = message.getTarget(Ametys.message.MessageTarget.THESAURUS);
		if (target != null && target.getParameters().id == this._thesaurusId)
		{
			this.close();
			return;
		}
		
		var target = message.getTarget(Ametys.message.MessageTarget.MICROTHESAURUS);
		if (target != null && this._isOnCurrentTree(target.getParameters().thesaurusId))
		{
			this._tree.loadMicrothesaurii();
			return;
		}
	},
	
    /**
     * Listener when the selected microthesaurus has changed.
     * Update the current reference table.
     */
	_onMicrothesaurusChange: function()
	{
		this.getParams().contentType = this.getMicrothesaurusId();
        this._tree.setReferenceTableId(this.getMicrothesaurusId());
	},
	
	/**
     * @private
     * Open the search tool
     * @param {String} path The path of metadata holding the parent
     * @param {String} contentId The content of double-clicked content
     */
    _openSearchTool: function (path, contentId)
    {
        var toolParams = this.getParams(),
            parentMetadataCriteria = "reference-" + path + "-eq";
	        values = {},
            values[parentMetadataCriteria] = contentId;
            
	    var toolFactoryId = 'uitool-microthesaurus',
	        searchToolId = "reference-table-search-ui." + toolParams.contentType;
	    
	    Ametys.tool.ToolsManager.openTool(toolFactoryId, {
	        contentDefaultTitle: toolParams.contentDefaultTitle,
	        contentLanguage: toolParams.contentLanguage,
	        contentType: toolParams.contentType,
	        values: values,
	        id: searchToolId,
	        startSearchAtOpening: true
	    }, 'cl');
    },
    
	/**
	 * Determines if the tool is concerned with the last update
	 * @param {String} thesaurusId The id of thesaurus concerned with the update
	 * @param {String} microthesaurusId The id of microthesaurus concerned with the update. Can be null.
	 * @return {Boolean} true if the tool is concerned with the last update
	 * @private
	 */
	_isOnCurrentTree: function (thesaurusId, microthesaurusId)
	{
		if (thesaurusId == null || this._thesaurusId != thesaurusId)
		{
			return false;
		}
		
		return microthesaurusId == null || this.getMicrothesaurusId() == microthesaurusId;
	}
});