/*
 *  Copyright 2017 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 synchronize contents
 * @private
 */
Ext.define('Ametys.plugins.contentio.search.SynchronizeContentAction', {
	singleton: true,
	
	/**
	 * Action function to be called by the controller.
	 * Will delete the contents registered by the controller.
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
	act: function (controller)
	{
		var contentIds = controller.getContentIds();
		
		if (contentIds.length == 1)
		{
			var targets = controller.getMatchingTargets();
	        var id = targets[0].getParameters().id;
            
            controller.serverCall(
                "getSyncCode", [id, controller.collectionId], Ext.bind(this._promptSyncCode, this),
                {
                    arguments: {
                        id: contentIds[0],
                        collectionId: controller.collectionId,
                        fieldLabel: controller['field-label']
                    },
                    errorMessage: {
                        msg: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_GET_SYNC_ERROR}}",
                        category: Ext.getClassName(this)
                    }
                }
            );
	    }
	},
	
	/**
	 * Callback function invoked after the getSyncCode method.
	 * @param {String} syncCode Current synchronization code
	 * @param {Object} args The callback arguments for the next prompt
	 * @private
	 */
	_promptSyncCode: function(syncCode, args)
	{
        Ametys.Msg.prompt(
            "{{i18n plugin.contentio:PLUGINS_CONTENTIO_GETCODE_BOX_TITLE}}", 
            args.fieldLabel, 
            function (btn, newSyncCode)
            {
                if (btn == 'ok')
                {
                    this._synchronize(newSyncCode, args);
                }
            },
            this,
            false,
            syncCode
        );
	},
	
	/**
	 * Callback function invoked after the prompt of synchronization code
	 * @param {String} syncCode Synchronization code
	 * @param {Object} args It contains the contentId
	 * @private
	 */
	_synchronize: function (syncCode, args)
	{
        // Ouverture du tool de logs
        Ametys.tool.ToolsManager.openTool(
            'uitool-server-logs',
            {
                id: "uitool-sync-logs", 
                category: "org.ametys.plugins.contentio.synchronize.SynchronizableContentsCollectionHelper", 
                title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_UITOOL_SYNC_LOGS}}"
            }, 
            "cr"
        );
        
        controller.serverCall(
            "synchronizeContent", [ args.collectionId, args.id, syncCode ], Ext.bind(this._synchronizeCb, this),
            {
                arguments: {
                    id: args.id
                },
                errorMessage: {
                    msg: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_SYNCHRO_ERROR}}",
                    category: Ext.getClassName(this)
                },
                priority: Ametys.data.ServerComm.PRIORITY_LONG_REQUEST
            }
        );
	},

    /**
     * @protected
     * Callback function after synchronizing the content
     * @param {boolean} hasErrors The server result
     * @param {Object} args It contains the contentId in 'id'
     */
	_synchronizeCb: function(hasErrors, args)
    {
    	if (hasErrors)
    	{
    		Ametys.Msg.show({
                title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_SYNCHRO_TITLE}}",
                msg: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_SYNCHRO_ERROR}}",
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
     		});
    	}
    	else
    	{
            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.CONTENT,
                    parameters: {ids: [args.id]}
                }
            });
            
    		Ametys.Msg.show({
               title: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_SYNCHRO_TITLE}}",
               msg: "{{i18n plugin.contentio:PLUGINS_CONTENTIO_SYNCHRO_SUCCESS}}",
               buttons: Ext.Msg.OK,
               icon: Ext.MessageBox.INFO
    		});
    	}
    }
});