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

/**
 * Menu for the images gallery
 */
Ext.define('Ametys.plugins.skinfactory.widgets.gallery.ImagesGallery', {
	extend: 'Ext.menu.Menu',
	
	/** 
	 * @cfg {boolean} enableLocalUpload True add local image. Defaults to false. 
	 */
	enableLocalUpload: false,
	
	constructor: function (config) 
	{
		this.callParent(arguments);
		
		this.on("show", this._onMenuShow, this);
		this.on('afterrender', this._onAfterRender, this);
		
		Ametys.message.MessageBus.on(Ametys.message.Message.LOADED, this._onSkinLoaded, this);
	},
	
	/**
	 * @private
	 * Listener invoked after rendering item.
	 * Apply the parent menu UI to the item
	 */
	_onAfterRender: function()
	{
		if (this.parentMenu && this.parentMenu.ui)
		{
			this.setUI(this.parentMenu.ui);
		}
	},
	
	/**
	 * @private
	 * Listener when the skin is loaded
	 * @param {Ametys.message.Message} message The loaded message on bus
	 */
	_onSkinLoaded: function (message)
	{
		var target = message.getTarget(Ametys.message.MessageTarget.SKIN);
        if (target)
        {
            // Remove old gallery items
            this.removeAll();
            
        	// Load the gallery items
    		var tool = Ametys.tool.ToolsManager.getTool("uitool-skinfactory");
            var skinName = tool.getSkinName();
            Ametys.plugins.skinfactory.skin.SkinDAO.getGalleryImages([skinName, this.getInitialConfig("paramId")], Ext.bind(this._loadItemsCb, this));
        }
	},
	
	/**
	 * Listener when a button is clicked
	 * @param {Ametys.ui.fluent.ribbon.controls.Button} button This button
	 * @private
	 */
	_onClick: function (button)
	{
		var uploaded = button.uploaded ? true : false;
		Ametys.plugins.skinfactory.skin.SkinActions.updateParameter(this.getInitialConfig("paramId"), button.imgHref, null, {uploaded: uploaded});
	},
	
	/**
	 * Listener when the menu of the button is showed.
	 * @param {Ext.menu.Menu} menu The menu.
	 */
	_onMenuShow: function (menu)
	{
		var currentValue = Ametys.plugins.skinfactory.SkinParametersManager.getParameterValue(this.getInitialConfig("paramId"));
		if (typeof (currentValue) == 'object')
		{
			currentValue = currentValue.path;
		}
		
        menu.items.each(function (groupPanel) {
            if (groupPanel.items)
            {
                groupPanel.items.each(function (btn) {
		            // If there is no gallery categories, we are directly on the gallery items
		            if (btn.imgHref)
		            {
		                btn.toggle(currentValue != null && btn.imgHref == currentValue);
		            }
                });
            }
        });
	},
	
	/**
	 * Create the gallery item from the server informations
	 * @param {Object[]} imagesData The images and groups informations
	 * @param {Object} currentGroup The current item group for images without a group in the imagesData parameter.
	 */
	_createGalleryItems: function (imagesData, currentGroup)
	{
		var me = this;
		Ext.Array.each(imagesData, function (imageData) {
			if (imageData.type && imageData.type == "group")
			{
				if (imageData.childs && imageData.childs.length > 0)
				{
					var group = {
						label: imageData.label,
						items: [],
						groups: []
					};
					
					me._createGalleryItems(imageData.childs, group);
					
					currentGroup.groups.push(group);
				}
			}
			else
			{
				var i = imageData.filename.lastIndexOf(".");
				var fileName =  i != -1 ? imageData.filename.substring(0, i) : imageData.filename;
				
				var button = Ext.create("Ametys.ui.fluent.ribbon.controls.Button", {
					text: fileName,
					tooltip: {
						title: fileName,
						image: Ametys.CONTEXT_PATH + imageData.thumbnailLarge,
						imageWidth: 100,
						imageHeight: 100,
						inribbon: false
					},
					
					icon: Ametys.CONTEXT_PATH + imageData.thumbnail,
					scale: 'large',
                    
                    uploaded: imageData.uploaded,
					imgHref: imageData.src,
					handler: Ext.bind(me._onClick, me),
					enableToggle: true,
					toggleGroup: 'photo-gallery-' + me.getId(),
					allowDepress: false
				});
				
				currentGroup.items.push(button);
			}
		});
	},
	
	/**
	 * Listener for the render event. Create the menu gallery
	 * @param {Object} response The images gallery informations.
	 * @private
	 */
	_loadItemsCb: function (response)
	{
		var items = [];
		
		if (response.gallery)
		{
			var rootGroup = {
				label: "{{i18n PLUGINS_SKINFACTORY_IMAGESGALLERY_GROUP_NONE}}",
				items: [],
				groups: []
			};
			this._createGalleryItems(response.gallery, rootGroup);
			
			if (rootGroup.items.length > 0)
			{
				var menuPanel = Ext.create("Ametys.ui.fluent.ribbon.controls.gallery.MenuPanel", {
					title: rootGroup.label, 
					items: rootGroup.items,
					
					width: 402,
					defaults: {
						width: 80
					}
				});
				items.push(menuPanel);
			}
			
			if (rootGroup.groups.length > 0)
			{
				Ext.Array.each(rootGroup.groups, function (group) {
					var menuPanel = Ext.create("Ametys.ui.fluent.ribbon.controls.gallery.MenuPanel", {
						title: group.label, 
						items: group.items,
						
						width: 402,
						defaults: {
							width: 80
						}
					});
					items.push(menuPanel);
				});
			}
		}
			
		if (response.uploadedGroup)
		{
			var group = {
				label: response.uploadedGroup.label,
				items: []
			};
			this._createGalleryItems(response.uploadedGroup.images, group);
			
			if (group.items.length > 0)
			{
				var menuPanel = Ext.create("Ametys.ui.fluent.ribbon.controls.gallery.MenuPanel", {
					title: group.label, 
					items: group.items,
					
					width: 402,
					defaults: {
						width: 80
					}
				});
				items.push(menuPanel);
			}
		}
		
		if (this.enableLocalUpload)
		{
			items.push(Ext.create("Ext.menu.Item", {
					text: "{{i18n PLUGINS_SKINFACTORY_UPLOAD_IMAGE}}",
					iconCls: 'ametysicon-file98',
					handler: Ext.bind(this._uploadImage, this)
				})
			);
		}
		
		this.add(items); 
	},
	
	/**
	 * Handler for the upload image item in the menu. Call the upload image action.
	 * @private
	 */
	_uploadImage: function ()
	{
		var tool = Ametys.tool.ToolsManager.getTool("uitool-skinfactory");
		var skinName = tool.getSkinName();
		Ametys.plugins.skinfactory.skin.SkinActions.uploadImage(skinName, this.getInitialConfig("paramId"));
	}
});