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

/**
 * Singleton class to handle actions on skin models.
 */
Ext.define('Ametys.plugins.skinfactory.model.SkinModelActions', {
    singleton : true,

    /**
     * Action called by the controller to import a new model from a zip file
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    'import': function (controller)
    {
    	Ametys.plugins.web.skin.helper.ImportSkinUI.open({
			url: Ametys.getPluginDirectPrefix("skinfactory") + '/administrator/model/upload',
			title: "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_IMPORT_LABEL}}",
			icon:  Ametys.getPluginResourcesPrefix("skinfactory") + '/img/model/import_16.png',
			helpMsg: "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_IMPORT_DIALOG_HINT}}",
			existFn: Ametys.plugins.skinfactory.model.SkinModelDAO.modelExists,
			existConfirmTitle: "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_IMPORT_TEST_EXIST_ALERT}}",
			existConfirmDesc: "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_IMPORT_TEST_EXIST_ALERT_DESC}}",
			importFn: Ext.bind (this._doImport, this)
		});
    },
    
    /**
	 * @private
	 * Import the uploaded model
	 * @param {Object} result the upload result
	 */
	_doImport: function (result)
	{
		var modelPath = result.tempDir + "/" + result.skinDir;
		Ametys.plugins.skinfactory.model.SkinModelDAO.importModel([result.skinName, modelPath], null, { waitMessage: true });
	},
	
    /**
     * Action called by the controller to export a model into a zip file
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    'export': function (controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            var url = Ametys.getPluginDirectPrefix('skinfactory') + "/administrator/model/export/" + targets[0].getParameters().name + ".zip";
            window.open(url);
        }
    },

    /**
     * Action called by the controller to generate a new skin from a model
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    generateSkin: function (controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            Ametys.plugins.web.skin.helper.GenerateSkinUI.open(targets[0].getParameters().name);
        }
    },

    /**
     * Action called by the skin menu to generate a new skin from a model
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    menuGenerateSkin: function (controller)
    {
        Ametys.plugins.web.skin.helper.GenerateSkinUI.open();
    },

    /**
     * Action called by the controller to reapply a model to all its skins
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    applyAll: function (controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            var me = this;

            Ametys.Msg.confirm("{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_APPLY_ALL_LABEL}}",
                "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_APPLY_ALL_CONFIRM}}",
                function(answer)
                {
                    if (answer == 'yes')
                    {
                        Ametys.plugins.skinfactory.model.SkinModelDAO.applyModelToAll([targets[0].getParameters().name], Ext.bind(me._applyAllCb, me), {});
                    }
                }
            );
        }
    },

    /**
     * Callback after reapplying a model to its skins
     * @param {Object} result the server result
     * @private
     */
    _applyAllCb: function(result)
    {
        if ((!result.unmodifiedSkins || result.unmodifiedSkins.length == 0) && (!result.unmodifiableSkins || result.unmodifiableSkins.length == 0))
        {
            Ametys.Msg.show({
	            title: "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_APPLY_ALL_LABEL}}",
	            msg: "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_APPLY_ALL_SUCCESS}}",
	            buttons: Ext.Msg.OK,
	            icon: Ext.MessageBox.INFO
	        });
        }
    },

    /**
     * Action called by the controller to filter skins from a model
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     * @param {Boolean} state The toggle state
     */
    filterSkins: function (controller, state)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            Ext.create("Ametys.message.Message",
            {
                type: state ? Ametys.message.Message.CREATED : Ametys.message.Message.DELETED,
                targets:
                {
                    id: Ametys.message.MessageTarget.SKINFILTER,
                    parameters:
                    {
                        id: targets[0].getParameters().name,
                        label: targets[0].getParameters().title
                    }
                }
            });
        }
    },

    /**
     * Action called by the controller to delete a model
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the function
     */
    'delete': function (controller)
    {
        var targets = controller.getMatchingTargets();
        if (targets.length > 0)
        {
            Ametys.Msg.confirm("{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_DELETE_LABEL}}",
                "{{i18n PLUGINS_SKINFACTORY_SKIN_MODEL_DELETE_WARNING}}",
                function(answer)
                {
                    if (answer == 'yes')
                    {
                    	// We could use 'Ametys.plugins.skinfactory.model.SkinModelDAO.delete' directly but delete is a keyword and it causes an error in IE8
                    	Ametys.executeFunctionByName ("Ametys.plugins.skinfactory.model.SkinModelDAO.delete", null, null, [targets[0].getParameters().name, targets[0]], null, {});
                    }
                }
            );
        }
    }
});