/*
 *  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
 * Singleton class defining the actions related to groups.
 */
Ext.define('Ametys.plugins.coreui.profiles.ProfilesActions', {
	singleton: true,
	
    /**
     * @property {String} CLIPBOARD_PROFILE Id of profile to store in clipboard
     */
    CLIPBOARD_PROFILE: "profile",
    
	/**
	 * Creates a profile.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	add: function (controller)
	{
		var context = controller.getInitialConfig('context') ? Ametys.getAppParameter(controller.getInitialConfig('context')) : null;
		Ametys.plugins.coreui.profiles.EditProfileHelper.add(context, Ext.bind(this._addCb, this));
	},
	
	/**
	 * Callback function invoked after profile creation
	 * @param {Object} profile The created profile
	 */
	_addCb: function (profile)
	{
		var tool = Ametys.tool.ToolsManager.getTool('uitool-profiles');
    	if (tool == null)
    	{
    		Ametys.tool.ToolsManager.openTool('uitool-profiles', {selectedProfiles: [profile.id]});
    	}
	},
	
	/**
	 * Rename a profile's properties
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	edit: function(controller)
	{
		var profileTarget = controller.getMatchingTargets()[0];
		if (profileTarget != null)
		{
			Ametys.plugins.coreui.profiles.EditProfileHelper.edit(profileTarget.getParameters().id);
		}
	},
	
	/**
	 * Delete groups
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	'delete': function (controller)
	{
		var profileTargets = controller.getMatchingTargets();
		if (profileTargets != null && profileTargets.length > 0)
		{
			Ametys.Msg.confirm("{{i18n PLUGINS_CORE_UI_PROFILES_DELETE_LABEL}}",
				"{{i18n PLUGINS_CORE_UI_PROFILES_DELETE_CONFIRM}}",
				Ext.bind(this._doDelete, this, [profileTargets, controller], 1),
				this
			);
		}
	},

	/**
	 * @private
	 * Callback function invoked after the 'delete' confirm box is closed
	 * @param {String} buttonId Id of the button that was clicked
	 * @param {Ametys.message.MessageTarget[]} targets The profiles message targets
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function 
	 */
	_doDelete: function(buttonId, targets, controller)
	{
		if (buttonId == 'yes')
		{
			var ids = Ext.Array.map(targets, function(target) {
				return target.getParameters().id;
			});
			
			if (ids.length > 0)
			{
				Ametys.plugins.core.profiles.ProfilesDAO.deleteProfiles([ids], null, {});
			}
		}
	},
	
	/**
	 * Copy the current selected profile's right in the clipboard.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling the action
	 */
    copy: function (controller)
    {
        var profileTarget = controller.getMatchingTargets()[0];
        if (profileTarget != null)
        {
            Ametys.plugins.core.profiles.ProfilesDAO.getProfile([profileTarget.getParameters().id, true], this._copyCb, {scope: this});
        }
    },
    
    
    /**
     * @private
     * Copy the profile's right in the clipboard.
     */
    _copyCb: function (profile)
    {
        if (profile && profile.rights)
        {
            Ametys.clipboard.Clipboard.setData (this.CLIPBOARD_PROFILE, {
                rights: profile.rights,
            });
        }
    },
    
    /**
     * Paste the rights stored in clipboard in the selected profile.
     * The new rights will override any existing right in the profile.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling the action
     */
    paste: function (controller)
    {
        var profileTarget = controller.getMatchingTargets()[0];
        if (profileTarget != null)
        {
            var clipboardData = Ametys.clipboard.Clipboard.getData();
            if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == this.CLIPBOARD_PROFILE)
            {
                Ametys.Msg.confirm("{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_TITLE}}",
                    "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_CONFIRM}}",
                    Ext.bind(this._doPaste, this, [profileTarget.getParameters().id, clipboardData[0].rights], 1),
                    this
                );
            }
            else
            {
                Ametys.Msg.show({
                    title: "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_TITLE}}",
                    msg: "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_EMPTY_CLIPBOARD}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.WARNING
                });
            }
        }
    },
    
    /**
     * @private
     */
    _doPaste: function(buttonId, profileId, rights)
    {
        if (buttonId == 'yes')
        {       
            Ametys.plugins.core.profiles.ProfilesDAO.editProfileRights([profileId, rights], this._pasteCb, {scope: this});
        }
    },
    
    /**
     * @private
     * Create a message if the paste was successful
     */
    _pasteCb: function (profile)
    {
        if (profile && !profile.error)
        {
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                parameters : {
                    major: true
                },
                targets: {
                    id: Ametys.message.MessageTarget.PROFILE,
                    parameters: {
                        id: profile.id,
                    }
                }
            })
        }
        else
        {
            Ametys.Msg.show({
                    title: "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_TITLE}}",
                    msg: "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_UNKNOWN_PROFILE}}",
                    buttons: Ext.Msg.OK,
                    icon: Ext.MessageBox.ERROR
                });
        }
    },
    
    /**
     * Create a new profile with the right stored in clipboard using the context provided by the controller, or none
     * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling the action
     */
    createFromClipboard: function (controller)
    {
        var clipboardData = Ametys.clipboard.Clipboard.getData();
        if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == this.CLIPBOARD_PROFILE)
        {
            var context = controller.getInitialConfig('context') ? Ametys.getAppParameter(controller.getInitialConfig('context')) : null;
            Ametys.plugins.coreui.profiles.EditProfileHelper.add(context, Ext.bind(
                function(profile) {
                    Ametys.plugins.core.profiles.ProfilesDAO.editProfileRights([profile.id, clipboardData[0].rights], this._addCb, {scope: this})
                },
                this));
        }
        else
        {
            Ametys.Msg.show({
                title: "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_TITLE}}",
                msg: "{{i18n PLUGINS_CORE_UI_PROFILES_PASTE_DIALOG_EMPTY_CLIPBOARD}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.WARNING
            });
        }
    },
	
	/**
	 * Export profiles.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	exportProfiles: function (controller)
	{
		var profileTargets = controller.getMatchingTargets();
		if (profileTargets != null && profileTargets.length > 0)
		{
			var ids = Ext.Array.map(profileTargets, function(target) {
				return target.getParameters().id;
			});
			
			if (ids.length > 0)
			{
				var args = {
		            'ids': ids.join()
		        };
				
				var appParameters = Ametys.getAppParameters();
				var additionParams = "";
		        Ext.Object.each(appParameters, function(key, value) {
		            additionParams += '&' + key + '=' + encodeURIComponent(value);
		        });
				
				Ametys.openWindow(Ametys.getPluginDirectPrefix('core') + '/rights/profiles/export.json?' + additionParams, args);
			}
		}
	},
	
	/**
	 * Import profiles.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	importProfiles: function (controller)
	{
        var uploadUrl = Ametys.getPluginDirectPrefix('core') + "/profile/import"
		var context = controller.getInitialConfig('context') ? Ametys.getAppParameter(controller.getInitialConfig('context')) : null;
        if (context)
        {
            uploadUrl += "?context=" + encodeURIComponent(context);
        }
		Ametys.helper.FileUpload.open({
             iconCls: 'ametysicon-id16 ametysicon-arrow-down-in',
             title: "{{i18n PLUGINS_CORE_UI_PROFILES_DIALOG_IMPORT_TITLE}}",
             helpmessage: "{{i18n PLUGINS_CORE_UI_PROFILES_DIALOG_FILE_TO_IMPORT_HINT}}",
             callback: Ext.bind(this._profileImportCb, this),
             filter: Ametys.helper.FileUpload.JSON_FILTER,
			 uploadUrl: uploadUrl
        });
	},
	
	/**
	 * @private
	 * Callback function invoked after profile import process is over.
	 * @param {String} id The file id.
     * @param {String} fileName The file name
     * @param {Number} fileSize The file size in bytes.
     * @param {String} viewhref
     * @param {String} downloadHref
	 * @param {Object} result contain the results of the import
	 * @param {String} result.error.message contain the error message if file was uploaded but could not be processed as profile
	 * @param {String} result.rightsNotAdded the list of rights exported not existing in this context
	 * @param {String[]} result.ids the list of imported profiles ids
	 */
	_profileImportCb: function (id, fileName, fileSize, viewhref, downloadHref, result)
	{
		if (result.error)
		{
			Ametys.notify({
                type: 'error',
                title: "{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_FAILURE_TITLE}}",
                description: result.error["message"] || "{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_FAILURE}}"
            });
		}
		else
		{
            if (result.unknownRights && result.unknownRights.length)
            {
                Ametys.notify({
	                type: 'warn',
	                title: "{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_UNKNOWN_RIGHTS_TITLE}}",
	                description: Ext.String.format("{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_UNKNOWN_RIGHTS}}", result.unknownRights.length, result.unknownRights.join(", "))
	            });
            }
            
            var msg = Ext.String.format("{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_SUCCESS}}", result.ids.length);
            if (result.renamedIds && result.renamedIds.length)
            {
                msg += "<br/><br/>";
                msg += Ext.String.format("{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_EXISTING_PROFILE_IDS}}", result.renamedIds.length, result.renamedIds.join(", "))
            }
            
			Ametys.notify({
                type: 'info',
                title: "{{i18n PLUGINS_CORE_UI_PROFILES_IMPORT_SUCCESS_TITLE}}",
                description: msg
            });
            
			var targets = [];
			for (const id of result.ids)
			{
				targets.push({
					id: Ametys.message.MessageTarget.PROFILE,
					parameters: {id: id}
				})
			}
			
			Ext.create('Ametys.message.Message', {
				type: Ametys.message.Message.CREATED,
				targets: targets
			});
			
			var tool = Ametys.tool.ToolsManager.getTool('uitool-profiles');
	    	if (tool == null)
	    	{
	    		Ametys.tool.ToolsManager.openTool('uitool-profiles', {selectedProfiles: [result.ids]});
	    	}
	    	else
	    	{
	    		tool.refresh();
	    	}
		}
	}
});