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

/**
 * @private
 * This panel displays the user's sites in a data view. 
 */
Ext.define('Ametys.plugins.web.SitesDialog', {
	extend: 'Ext.panel.Panel',
	
	/**
     * @cfg {String} contextPath The context path of application
     */
    
    /**
     * @cfg {String} workspaceContext The workspace context path
     */
	
	title: "{{i18n workspace.web:WORKSPACE_WEB_HOME_PAGE_SITES_TITLE}}",
	
    bodyPadding : "20 20",
    border: true,
    cls : "ametys-sites-dialog",
    width : 700,
    scrollable: true,
    
	layout : {
      type : "vbox",
      align : "stretch"
    },
    
    initComponent: function ()
    {
    	this.items = [
	    	{
	    		xtype: 'container',
	    		html: "{{i18n workspace.web:WORKSPACE_WEB_HOME_PAGE_SITES_LIST}}"
	    	}, 
	    	Ext.create('Ametys.plugins.web.SitesDialog.SitesView', {
	    		contextPath: this.contextPath,
	    		workspaceContext: this.workspaceContext,
	    		maxHeight: 400,
	    		scrollable: true,
	    		
	    		store: {
	    			listeners: {'load': {fn: this._onLoadSites, scope: this}}
	    		}
	    	})
    	]
    	
    	this.callParent(arguments);
    },
    
    /**
     * @private
     * Callback when sites are loaded
     * @param {Ext.data.Store} store The store loaded
     * @param {Ext.data.Model[]} records The loaded records
     */
    _onLoadSites:function (store, records)
    {
    	if (records.length == 0)
    	{
    		this.items.get(0).update("{{i18n workspace.web:WORKSPACE_WEB_HOME_PAGE_NO_SITE}}");
    	}
    }
});

/**
 * @private
 * Panel of user's sites home page
 */
Ext.define('Ametys.plugins.web.HomeSitesPage', {
    extend: 'Ext.panel.Panel',
    
    /**
     * @cfg {String} contextPath The context path of application
     */
    
    /**
     * @cfg {String} workspaceContext The workspace context path
     */
    
    cls : "ametys-sites-screen",
    
    title: "Ametys",
    /**
     * @inheritdoc Ext.panel.Header#cfg-titleAlign
     * @private
     */
    titleAlign : "center",
    
    frameHeader : false,
    
    layout : {
      type : "vbox",
      align: "stretch",
      pack: "center"
    },
    
    bodyStyle: {
    	padding: '20px 12% 20px 12%'
    },
    
    initComponent: function ()
    {
    	this.items = [{
        	xtype: 'container',
        	flex: 1,
        	layout : {
    	      type : "hbox",
    	      align: "middle"
    	    },
        	items:[
            	Ext.create('Ametys.plugins.web.SitesDialog', {
            		contextPath: this.contextPath,
            		workspaceContext: this.workspaceContext
            	})
            ]
        }]
    	
    	this.callParent(arguments);
    }
    
});

/**
 * @private
 * The model for the {@link Ametys.plugins.web.SitesDialog.SitesView} data view
 */
Ext.define('Ametys.plugins.web.SitesDialog.SitesView.Site', { 
    extend: 'Ext.data.Model', 
    fields: [ 
        { name: 'id', type: 'string' }, 
        { name: 'name', type: 'string' }, 
        { name: 'valid', type: 'boolean' }, 
        { 
        	name: 'text', 
        	type: 'string', 
        	calculate: function (data) {
        		if (Ext.isEmpty(data.title))
        		{
        			return data.name;
        		}
        		else
        		{
        			return data.title + ' (' + data.name + ')';
        		}
        	},
        	depends: ['name', 'title']
        },
        { name: 'url', type: 'string' },
        { name: 'title', type: 'string' },
        { name: 'type', type: 'string' },
        { name: 'typeLabel', type: 'string' },
        { name: 'description', type: 'string' },
        { name: 'iconSmall', type: 'string' },
        { 
        	name: 'icon', 
        	type: 'string',
        	depends: ['iconLarge', 'invalidIconLarge', 'valid'],
        	calculate: function (data) {
        		return data.valid ?  data.iconLarge : data.invalidIconLarge 
        	}
        },
        { name: 'iconLarge', type: 'string' },
        { name: 'invalidIconSmall', type: 'string' },
        { name: 'invalidIconLarge', type: 'string' }
    ]
}); 

/**
 * @private
 * This data view is used for user's sites.
 */
Ext.define('Ametys.plugins.web.SitesDialog.SitesView', {
	extend: 'Ext.view.View',
	
	/**
     * @cfg {String} contextPath The context path of application
     */
    
    /**
     * @cfg {String} workspaceContext The workspace context path
     */
	
	constructor: function(config)
	{
		Ext.applyIf (config, {
			
			cls: 'sites-view',
			border: false,
			scrollable: true,
			
            selModel: {
                mode: 'SINGLE'
            },
	        
			overItemCls:'x-view-over',
	        itemSelector:'div.sites-view-item',
		    
		    tpl: new Ext.XTemplate(
		    	'<tpl for=".">',
			    	'<div class="sites-view-item" id="{name}">',
				        '<div><img src="' + config.workspaceContext + '{icon}"></div>',
				        '<div class="site-text">',
				        	'<strong>{title}</strong><em> ({name})</em><br/>',
				        	'<tpl if="description != \'\'">{description}<br/></tpl>',
				        	'<a href="{url}" target="_blank" class="url">{url}</a>',
				        '</div>',
				    '</div>',
				    '<tpl if="xindex % 2 == 0"><div style="clear: left"></div></tpl>',
			    '</tpl>'
		    ),
		        
			store: Ext.create('Ext.data.Store', Ext.applyIf (config.store, {
				model: 'Ametys.plugins.web.SitesDialog.SitesView.Site',
				autoLoad: true,
		        proxy: {
		        	type: 'ajax',
					url: config.workspaceContext + '/user/sites.json',
		        	reader: {
		        		type: 'json',
						rootProperty: 'sites'
		        	}
		        },
		        sorters: [ { property: 'label', direction: "ASC" }]
			})),
			
			listeners: {
				'selectionchange': {fn: this.openSite, scope: this}
			}
		});
		
		this.callParent(arguments);
	},
	
	prepareData: function(data, index, record) {
        if(Ext.isObject(data)) {
            data.xindex = index + 1;
        }
        return this.callParent(arguments);
    },
	
	/**
	 * Open back-office application with the selected site
	 */
	openSite: function (sm, selected)
	{
		if (selected.length > 0)
		{
			var siteName = selected[0].get('name');
			window.location.href = this.contextPath + '/' + siteName + '/index.html';
		}
	}
});