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

/**
 * General actions to manage project.
 * @private
 */
Ext.define('Ametys.plugins.workspaces.project.actions.ProjectActions', {
    singleton: true,
    
    /**
     * Create a new project
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    add: function(controller)
    {
        Ametys.plugins.workspaces.project.helper.ProjectEdition.act(
            'new',
            null,
            this._addCb,
            this
        );
    },
    
    /**
     * @private
     * Callback function called after creating a project
     * @param {String} id The project id
    */
    _addCb: function (id)
    {
    	function callback (project)
    	{
    		Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.CREATED,
                targets: [{
                    id: Ametys.message.MessageTarget.WORKSPACES_PROJECT,
                    parameters: {
                    	project: project
                    }
                }]
            });
    		
    		var site = project.getSite();
    		if (site != null)
    		{
                var siteId = site.id,
                    siteName = site.name,
                    siteTitle = site.title;
                    
                // The project workspace has been created, send site created message
                Ext.create('Ametys.message.Message', {
                    type: Ametys.message.Message.CREATED,
                    targets: [{
                        id: Ametys.message.MessageTarget.SITE,
                        parameters: {
                            id: siteId,
                            name: siteName
                        }
                    }]
                });
                
                // Enable to choose users populations allowed to connect to the application for this site
                
                var contextBO = '/sites/' + siteName;
                var contextFO = '/sites-fo/' + siteName;
                Ametys.plugins.web.populations.PopulationActions.openLinkToSiteDialog(contextBO, contextFO, siteName, siteTitle);
                
                // Open site configuration tool to allow the user to configure the site
                // of the project workspace
                Ametys.tool.ToolsManager.openTool('uitool-admin-site-config', {id: siteName, siteId: siteId, siteName: siteName, siteTitle: siteTitle});
    		}
    		else
    		{
    			// No site
    			Ametys.Msg.show({
                    title: "{{i18n PLUGINS_WORKSPACES_PROJECT_ADD_PROJECT_ERROR}}",
                    message: "{{i18n PLUGINS_WORKSPACES_PROJECT_ADD_PROJECT_ERROR_SITE_NOT_FOUND}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.Msg.ERROR
                });
    		}
    	}
    	
    	Ametys.plugins.workspaces.project.ProjectDAO.getProject(id, callback);
    },
    
    /**
     * Edit a project
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    edit: function(controller)
    {
    	var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
        	var me = this;
        	function callback (project)
        	{
        		Ametys.plugins.workspaces.project.helper.ProjectEdition.act(
                        'edit',
                        project,
                        me._editCb,
                        me
                    );
        	}
        	
        	Ametys.plugins.workspaces.project.ProjectDAO.getProject(targets[0].getParameters().id, callback);
        }
    },
    
    /**
     * @private
     * Callback function called after the edition of a project
     * @param {String} id The project id
    */
    _editCb: function (id)
    {
        // send modified message
        Ext.create('Ametys.message.Message', {
            type: Ametys.message.Message.MODIFIED,
            targets: [{
                id: Ametys.message.MessageTarget.WORKSPACES_PROJECT,
                parameters: {
                    id: id
                }
            }]
        });
    },
    
    /**
     * Open the site's managment screen
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    openSite: function(controller)
    {
        var target = controller.getMatchingTargets()[0];
        if (target != null && target.getParameters().siteName)
        {
            function callback (project)
            {
                var site = project.getSite();
                Ametys.tool.ToolsManager.openTool('uitool-admin-sites', {id: site.id});
            }
            
            Ametys.plugins.workspaces.project.ProjectDAO.getProject(target.getParameters().id, callback);
        }
    },
    
    /**
     * Open the site's configuration of the projet
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    openConfig: function(controller)
    {
    	var target = controller.getMatchingTargets()[0];
        if (target != null && target.getParameters().siteName)
        {
        	function callback (project)
        	{
        		var site = project.getSite();
        		Ametys.tool.ToolsManager.openTool('uitool-admin-site-config', {id: site.name, siteId: site.id, siteName: site.name, siteTitle: site.title});
        	}
        	
        	Ametys.plugins.workspaces.project.ProjectDAO.getProject(target.getParameters().id, callback);
        }
    },
    
    /**
     * Delete the selected projects
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    remove: function(controller)
    {
        var targets = controller.getMatchingTargets();
        
        if (targets.length > 0)
        {
            Ametys.Msg.confirm(
                "{{i18n PLUGINS_WORKSPACES_PROJECT_DELETE_PROJECT_DIALOG_TITLE}}",
                "{{i18n PLUGINS_WORKSPACES_PROJECT_DELETE_PROJECT_DIALOG_CONFIRM}}",
                function(btn) {
                    if(btn == 'yes')
                    {
                        this._doRemove(targets);
                    }
                },
                this
            );
        }
        
    },
    
    /**
     * Callback function invoked after the projects deletion confirm box is validated
     * @param {Ametys.message.MessageTarget[]} targets The project targets
     * @private
     */
    _doRemove: function (targets)
    {
        var ids = [];
        
        ids = Ext.Array.map(targets, function(target) {
            return target.getParameters().id;
        });
        
        Ametys.data.ServerComm.callMethod({
            role: 'org.ametys.plugins.workspaces.project.ProjectManager',
            methodName: 'deleteProjectsByIds',
            parameters: [ids],
            callback: {
                scope: this,
                handler: this._removeCb,
                arguments: {
                	targets: targets
                }
            },
            waitMessage: true,
            errorMessage: true
        });
        
    },
    
    /**
     * Delete projects callback, processed after server side deletion.
     * @param {Object} response the server response
     * @param {String[]} response.deleted identifiers of deleted projects
     * @param {String[]} response.unknowns identifiers of projects that were not found
     * @param {Object} args the callback arguments
     */
    _removeCb: function(response, args)
    {
    	var targets = args.targets;
    	
    	var deletedProjects = response.deleted;
    	if (deletedProjects.length > 0)
		{
			var deletedTargets = [];
			
			for (var i=0; i < deletedProjects.length; i++)
			{
				for (var j=0; j < targets.length; j++)
				{
		        	if (targets[j].getParameters().id == deletedProjects[i].id)
					{
		        		deletedTargets.push(targets[j]);
					}
				}
				
				// Remove project from navigation history
				Ametys.navhistory.HistoryDAO.removeEntry (deletedProjects[i].id);
				
				// Notify content deletion
		        Ametys.notify({
		            type: 'info',
		            iconGlyph: 'ametysicon-file98',
		            title: "{{i18n PLUGINS_WORKSPACES_NOTIFICATION_DELETE_PROJECT_TITLE}}",
		            description: Ext.String.format("{{i18n PLUGINS_WORKSPACES_NOTIFICATION_DELETE_PROJECT_DESCRIPTION}}", deletedProjects[i].title)
		        });
		        
		        // Fires site deletion
		        var deletedSites = deletedProjects[i].sites;
		        if (deletedSites && deletedSites.length > 0)
		        {
		            var siteTargets = Ext.Array.map(deletedSites, function(site) {
		                return {
		                    id: Ametys.message.MessageTarget.SITE,
		                    parameters: {
		                        id: site.id,
		                        name: site.name
		                    }
		                };
		            });
		            
		            Ext.create('Ametys.message.Message', {
		                type: Ametys.message.Message.DELETED,
		                targets: siteTargets
		            });
		        }
			}
			
			// Fires deleted event
			Ext.create("Ametys.message.Message", {
				type: Ametys.message.Message.DELETED,
				targets: deletedTargets
			});
		}
    },
    
    /**
     * Open the site of a project workspace.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    openProjectWorkspace: function(controller)
    {
    	var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
	    	var me = this;
	    	function callback (project)
	    	{
	    		var site = project.getSite();
	    		if (!project.getValid())
	    		{
	    			Ametys.Msg.show({
                        title: "{{i18n PLUGINS_WORKSPACES_PROJECT_OPEN_PROJECT_WORKSPACE_ERROR}}",
                        message: "{{i18n PLUGINS_WORKSPACES_PROJECT_OPEN_PROJECT_WORKSPACE_ERROR_NOT_VALID}}",
                        buttons: Ext.Msg.OK,
                        icon: Ext.Msg.ERROR
                    });
	    		}
	    		else if (site == null)
	    		{
	    			 Ametys.Msg.show({
                         title: "{{i18n PLUGINS_WORKSPACES_PROJECT_OPEN_PROJECT_WORKSPACE_ERROR}}",
                         message: "{{i18n PLUGINS_WORKSPACES_PROJECT_OPEN_PROJECT_WORKSPACE_ERROR_SITE_NOT_FOUND}}",
                         buttons: Ext.Msg.OK,
                         icon: Ext.Msg.ERROR
                     });
	    		}
	    		else
	    		{
	    			Ametys.openWindow(site.url);
	    		}
	    	}
	    	
	    	Ametys.plugins.workspaces.project.ProjectDAO.getProject(targets[0].getParameters().id, callback);
        }
    }
});