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

/**
 * Singleton class to handle export action to CDM-fr.
 * @private
 */
Ext.define('Ametys.plugins.odf.cdmfr.ExportCDMfr', {
	singleton: true,

 	/**
	 * Exports to CDM-fr
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	act: function (controller)
	{
        var target = controller.getMatchingTargets()[0];
        
        var params = { id: target.getParameters().id };
        Ext.Object.each(Ametys.getAppParameters(), function(key, value) {
		    if (Ext.isString(value)) 
            {
		        params[key] = value;
		    }
		});

        Ametys.openWindow(Ametys.getPluginDirectPrefix('odf') + '/export-cdmfr.xml', params);
	},

    /**
     * Publish CDM-fr
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    publish: function (controller)
    {
        Ametys.Msg.confirm(
            "{{i18n plugin.odf:CONTENT_REPUBLISH_LABEL}}",
            "{{i18n plugin.odf:CONTENT_REPUBLISH_CONFIRM_MSG}}",
            function (answer)
            {
                if (answer == 'yes')
                {
                    var targetIds = controller.getMatchingTargets().map(function(t) {
                        return t.getParameters().id;
                    });

                    controller.serverCall('publish', [targetIds], Ext.bind(this._publishCB, this), { waitMessage: true });
                }
            },
            this
        );
    },

    /**
     * Publish CDM-fr callback
     * @param {Object} results The publish results
     */
    _publishCB: function(results)
    {
        if (results["error"])
        {
            let error = results["error"];
            Ametys.Msg.show({
                title: "{{i18n plugin.odf:CONTENT_REPUBLISH_LABEL}}",
                msg: error == "no-right" ? "{{i18n plugin.odf:CONTENT_REPUBLISH_RIGHT_ERROR}}" : "{{i18n plugin.odf:CONTENT_REPUBLISH_OTHER_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.Msg.ERROR
            });
        }
    }
});