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

/**
 * Sitemap and pages context for profile assignments.
 */
Ext.define('Ametys.plugins.web.profiles.PageRightAssignmentContext', {
    extend: 'Ametys.plugins.coreui.profiles.AbstractRightAssignmentContext',
    
    /**
     * @property {String[]} The rights to check on pages.
     */
    pageRights: [],
    
    constructor: function (config)
    {
    	this.callParent(arguments);
    	
    	this.pageRights = !Ext.isEmpty(config['page-rights']) ? config['page-rights'].split(',') : [];
    },
    
    /**
     * @private
     * @property {Ametys.web.sitemap.SitemapTree} _tree The sitemap tree
     */
    
    getComponent: function()
    {
        this._langCombo = Ametys.cms.language.LanguageDAO.createComboBox({
            itemId: 'page-assignment-languages',
            fieldLabel: "{{i18n PLUGINS_WEB_TOOL_SITEMAP_SITEMAPTOOL_LANGUAGE}}",
            flex: 1,
            
            synchronize: true,
            listeners: {
                'change': Ext.bind(this._onChangeLang, this)
            }
        });
        
        this._tree = this._createSitemapTreePanel(this._langCombo.getValue());
        
        return Ext.create ('Ext.panel.Panel', {
            border: false,
            
            layout: 'fit',
            
            // Languages combo box
            dockedItems: [{
                dock: 'top',
                xtype: 'toolbar',
                layout: {
                    type: 'hbox',
                    align: 'stretch'
                },
                border: false,
                
                defaults : {
                    cls: 'ametys',
                    labelWidth: 55,
                    labelSeparator: ''
                },
                
                items: this._langCombo
            }],
            
            items: this._tree
        });
    },
    
    initialize: function()
    {
        this._tree.initialize(Ext.bind(this._refreshCb, this));
    },
    
    isSupported: function (message)
    {
    	return message.getTargets(/^page|sitemap$/).length > 0;
    },
    
    initContext: function (message)
    {
    	this._pathToSelect = null;
    	this._sitemapToSelect = null;
    	
    	var pageTarget = message.getTarget(Ametys.message.MessageTarget.PAGE);
    	if (pageTarget != null)
    	{
    		this._pathToSelect = pageTarget.getParameters().path;
    		return;
    	}
    	
    	var sitemapTarget = message.getTarget(Ametys.message.MessageTarget.SITEMAP);
    	if (sitemapTarget != null)
    	{
    		this._sitemapToSelect = sitemapTarget.getParameters().name;
    	}
    },
    
    /**
     * Listens when a language is changed.
     * @param {Ext.form.field.Field} field The field
     * @param {Object} newValue The new language value.
     * @param {Object} oldValue The original value.
     * @private
     */
    _onChangeLang: function(field, newValue, oldValue)
    {
        // Reload sitemap
    	this._pathToSelect = null;
    	this._sitemapToSelect = null;
    	
        this._tree.setSitemapName(newValue, Ext.bind(this._refreshCb, this));
    },
    
    /**
     * @private
     * Callback function after (re)loading the tree
     */
    _refreshCb: function()
    {
        var me = this;
        window.setTimeout(function() {
        	if (me._pathToSelect != null)
        	{
        		me._tree.selectByPath(me._tree.getRootNode().get('name') + '/' + me._pathToSelect);
        	}
        	else if (me._sitemapToSelect != null)
        	{
        		me._langCombo.setValue(me._sitemapToSelect);
        	}
        	else
        	{
        		// Select root node
        		me._tree.getSelectionModel().select(0);
        	}
        }, 1);
    },
    
    /**
     * @private
     * Draw the tree panel for the sites
     * @param {String} defaultLang the default sitemap name
     */
    _createSitemapTreePanel: function(defaultLang)
    {
        return Ext.create('Ametys.web.sitemap.SitemapTree', {
            sitemapContext: defaultLang,
            defaultSitemapName: defaultLang,
            rights: this.pageRights,
            
            listeners: {
                'selectionchange': Ext.bind(this._onSelectionChanged, this)
            }
        });
    },
    
    /**
     * @private
     * Listener when the selection in the tree has changed
     * @param {Ext.selection.Model} model The selection model
     * @param {Ext.data.Model[]} selected The selected records
     */
    _onSelectionChanged: function(model, selected)
    {
        // Check it is not too soon to fire the event (if we do not loaded the root node yet for example)
        if (selected.length > 0)
        {
            var pageOrSitemap = selected[0],
                object = pageOrSitemap.get('id'),
                title = pageOrSitemap.get('title'),
                name = pageOrSitemap.get('name'),
                readOnly = !Ext.String.startsWith(object, "sitemap://") && pageOrSitemap.get('modifiable') === false,
                inheritanceNotAvailable = Ext.String.startsWith(object, "sitemap://");
            
            var hintTextContext = Ext.String.startsWith(object, "sitemap://") ? 
            	"{{i18n PLUGINS_WEB_RIGHT_ASSIGNMENT_CONTEXT_PAGES_HINT_SITEMAP}} <b>" + name + "</b>"
                : "{{i18n PLUGINS_WEB_RIGHT_ASSIGNMENT_CONTEXT_PAGES_HINT_PAGE}} <b>" + Ext.String.escapeHtml(title) + "</b>";
            
            this._changeObjectContext(object, hintTextContext, readOnly, inheritanceNotAvailable);
        }
    }
});