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

/**
 * @private
 * Class allowing to select the icon amongst a list of icons for a marker of the {@link Ametys.plugins.maps.GMapPanel}
 */
Ext.define('Ametys.plugins.maps.MarkerIconsDialog', {
	extend: 'Ametys.window.DialogBox',
	
	/**
	 * @private 
	 * @property {Ext.view.View} _dataView the data view of the icons
	 */
	
	/**
	 * @private
	 * @property {Function} _saveFn the function invoked to save the selected marker's icon
	 */
	
	constructor: function(config)
	{
		this._dataView = this._createDataView();
		this._saveFn = config.saveFn;
		
		config = Ext.applyIf({
	        layout: 'fit',
	        
	        title: "{{i18n PLUGINS_MAPS_HELPER_PIN_ICONS_DIALOG_TITLE}}",
	        width: 350,
	        height: 250,
	        closeAction:'hide',
	        scrollable: false,
	        alwaysOnTop: true,
	        
	        items: [this._dataView],
	        
	        closeAction: 'hide',
	        
	        referenceHolder: true,
	        defaultButton: 'validate',
	        
	        buttons: [{
	        	reference: 'validate',
	            text: "{{i18n PLUGINS_MAPS_HELPER_PIN_ICONS_DIALOG_OK_BTN}}", 
	            handler: this._ok,
	            scope: this
	        }, {
	            text: "{{i18n PLUGINS_MAPS_HELPER_PIN_ICONS_DIALOG_CANCEL_BTN}}",
	            handler: function () { this.hide(); },
	            scope: this
	        }]        
	    }, config);
		
		this.callParent(arguments);
	},
	
	/**
	 * @private
	 * Create the data view for the markers' icons
	 * @return {Ext.view.View} the icons' data view
	 */
	_createDataView: function()
	{
		var dataView = Ext.create ('Ext.view.View', 
		{
			itemSelector: 'div.thumb-wrap',
			scrollable: true,
			cls: 'pin-icons-dv',
			
			selModel: {
                mode: 'SINGLE'
            },
			
            border: false,
			overItemCls: 'x-view-over',
			selectedItemCls: 'x-view-over',
			
			store:  Ext.create('Ext.data.Store', 
					{
						autoDestroy: true,
						model: 'Ametys.plugins.maps.MarkerIconsDialog.MarkerIcon',
						
						proxy: {
							type: 'ametys',
							plugin: 'maps',
						    url: 'poi/list.json',
						    reader: {
						    	type: 'json',
						    	rootProperty: 'icons'
						    }
					    }
					}),
			
			tpl: new Ext.XTemplate(
				'<tpl for=".">',
					'<div class="thumb-wrap" id="{name}">',
						'<div class="thumb">',
							'<img src="{url}" class="thumb-img">',                                      
						'</div>',
					'</div>',
				'</tpl>'
			)
		});
		
		return dataView;
	},
	
	/**
	 * @private
	 * Load the icons of the store 
	 * @param {String} icon the name of the selected icon 
	 */
	_loadIcons: function (icon)
	{
		this._dataView.getStore().load({callback: Ext.bind(this._selectAndFocusIcon, this, [icon], false)});
	},
	
	/**
	 * @private
	 * Select the given icon in the data view and focuses it
	 * @param {String} icon the name of the selected icon 
	 */
	_selectAndFocusIcon: function (icon)
	{
		var store = this._dataView.getStore();
		// Select first icon if there is no previous selection
		var actualIcon = icon ? store.getById(icon): store.getById('pin');
		
		this._dataView.select(actualIcon);
		this._dataView.focusNode(actualIcon);
	},
	
	/**
	 * @private
	 * Function invoked when clicking the 'ok' button, saving the selected marker
	 */
	_ok: function ()
	{
		if (Ext.isFunction(this._saveFn))
		{
			var iconNodes = this._dataView.getSelectedNodes();
			if (iconNodes && iconNodes.length > 0)
			{
				var icon = this._dataView.getRecord(iconNodes[0]);
				this._saveFn (icon.data.name);
			}
			else
			{
				this._saveFn (null);
			}
		}
		
		this.hide();
	}
});