/*
 *  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 step of {@link Ametys.plugins.web.page.AddPageWizard} wizard allow to select tags.
 */
Ext.define("Ametys.plugins.web.page.AddPageWizard.TagsCard", {
	
	extend: "Ametys.plugins.web.page.AddPageWizard.Card",
    
    name: "tags",
	
	createPanel: function ()
	{
		this._cardPanel = Ext.create ('Ext.Panel', {
			layout: { 
				type: 'vbox', 
				align: 'stretch' 
			},
			padding: 0,
		    border: false,
		    
		    items: [
		            {
				    	xtype: 'component',
				    	cls: 'a-text',
				    	html: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['tags']['help']
				    },
				    {
				    	// The real tag tree will be inserted later here
				    	id: 'add-page-tags-card-treepanel',
				    	xtype: 'component',
				    	flex: 1
				    }
		    ]
		});
		
		return this._cardPanel;
	},
	
	apply: function (fullModel, callback)
	{
		if (fullModel['tags'] && fullModel['tags'].length > 0)
		{
			var contentIds = fullModel["content-id"] ? [fullModel["content-id"]] : [];
			var pageIds  = [fullModel["page-id"]];
			
			var opts = {
				scope: this,
				waitMessage: {
					target: this.getUI().ownerCt,
					msg: Ametys.plugins.web.page.AddPageWizard.getInitialConfig('i18n')['tags']['wait-message']
				},
				arguments: {
					callback: callback
				}
			}
			
			Ametys.web.page.PageDAO.tag([ pageIds, contentIds, fullModel['tags'], "INSERT", Ametys.getAppParameters() ], this._tagCb, opts);
		}
		else
		{
			callback (true);
		}
	},
	
	/**
	 * @private
	 * Callback function invoked after tagging page (and content)
	 * @param {Object} response the serveur response
	 * @param {Object} args the callback arguments
	 */
	_tagCb: function (response, args)
	{
		args.callback (true);
	},
	
	getUI: function ()
	{
		return this._cardPanel;
	},
	
	resetModel: function (callback)
	{
		this._model = {};
		this._model["tags"] = Ametys.plugins.web.page.AddPageWizard.getInitialConfig('default-tags') || [];
	
	    callback();
	},
	
	updateModel: function ()
	{
		var selectedTags = [];
		
		var currentTreePanel = Ext.getCmp("add-page-tags-card-treepanel");
		var selNodes = currentTreePanel.getChecked();
		for (var i=0; i < selNodes.length; i++)
		{
			selectedTags.push(selNodes[i].get('name'));
		}
		
		this._model['tags'] = selectedTags;
	},
	
	onEnter: function()
	{
		var fullModel = Ametys.plugins.web.page.AddPageWizard.getModel();
		
		var tagsFilter = this.getTagsFilters(fullModel);
        var targetType = this.getTargetType(fullModel);
		
		var currentTreePanel = Ext.getCmp("add-page-tags-card-treepanel");
		if (currentTreePanel.filterTarget != tagsFilter || currentTreePanel.targetType != targetType)
		{
			var treeOwnerCt = currentTreePanel.ownerCt;
			var treePosition = treeOwnerCt.items.indexOf(currentTreePanel);
			
			// remove current tree
			currentTreePanel.destroy();
			
			// remove current tree
			var tagsTree = Ext.create('Ametys.plugins.cms.tag.TagsTreePanel', {
				flex: 1,
				id: "add-page-tags-card-treepanel",
				
	            targetType: targetType,
	            filterTarget: tagsFilter,
	            
	            plugin: 'web',
	            url: 'tags.json',
	            
	            checkMode: true,
	            
	            listeners: {
			    	'checkchange': Ext.bind(Ametys.plugins.web.page.AddPageWizard._onChange, Ametys.plugins.web.page.AddPageWizard),
			    	'load': {fn: this._onLoad, scope: this}
				}
	        });
			
			treeOwnerCt.insert(treePosition, tagsTree);
		}	
		
		if (!this.shouldDisplayCard())
		{
			this._cardPanel.hide();
		}
	},
    
    getTagsFilters: function(fullModel)
    {
        var hasContent = this._hasContent(fullModel);
        var hasRightOnContentTag = hasContent && fullModel["right-tag-content-private"];
        var hasRightOnPublicContentTag = hasContent && fullModel["right-tag-content"];
        var hasRightOnPageTag = fullModel["right-tag-page-private"];
        var hasRightOnPublicPageTag = fullModel["right-tag-page"];
        
        var tagsFilter = [];
        if (!hasRightOnPageTag)
        {
            if (hasRightOnPublicPageTag)
            {
                // disable private page tags
                tagsFilter.push("PAGE_PRIVATE")
            }
            else
            {
                // disable all page tags
                tagsFilter.push("PAGE")
            }
        }
        
        if (hasContent)
        {
            if (!hasRightOnContentTag)
            {
                if (hasRightOnPublicContentTag)
                {
                    // disable private content tags
                    tagsFilter.push("CONTENT_PRIVATE")
                }
                else
                {
                    // disable all content tags
                    tagsFilter.push("CONTENT")
                }
            }
        }
        
        return tagsFilter;
    },
    
    getTargetType: function(fullModel)
    {
        return this._hasContent(fullModel) ? null : "PAGE";
    },
	
	/**
	 * Listener on load of record
	 * @param {Ext.data.TreeStore} store The tree store
	 * @param {Ext.data.TreeModel[]} records the loading
	 * @param {Boolean} successful True if the operation was successful.
	 * @param {Ext.data.Operation} operation The operation that triggered this load.
	 * @param {Ext.data.NodeInterface} node The node that was loaded.
	 */
	_onLoad: function (store, records, successful, operation, node)
	{
		if (node.isRoot())
		{
			this.updateUI();
		}
		Ametys.plugins.web.page.AddPageWizard._onChange();
	},
	
	updateUI: function (callback)
	{
        var values = this._model['tags']
                        || Ametys.plugins.web.page.AddPageWizard.getInitialConfig('default-tags')
                        || Ametys.plugins.web.page.AddPageWizard.getInitialConfig('default-selected-tags')
                        || [];
        
        var currentTreePanel = Ext.getCmp("add-page-tags-card-treepanel");
        currentTreePanel.setValues(values);
        
        if (Ext.isFunction(callback))
        {
            callback(true);
        }
	},
	
	isModelOk: function (fullModel)
	{
		var currentTreePanel = Ext.getCmp("add-page-tags-card-treepanel");
		return currentTreePanel && !currentTreePanel.getStore().isLoading();
	},
	
	isAvailable: function (fullModel)
	{
		return fullModel["right-tag-page"] 
            || fullModel["right-tag-page-private"]
		    || (
                fullModel["page-type"] == "template" && fullModel["pagecontent-type"] == "contenttype" 
                && (
                    fullModel["right-tag-content"] 
                    || fullModel["right-tag-content-private"]
                   )
                );
	},
    
    _hasContent: function (fullModel)
    {
        return fullModel["page-type"] == "template" && fullModel["pagecontent-type"] == "contenttype";
    }
	
});