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

/**
 * This UI helper provides a dialog to import contents from server directory
 */
Ext.define('Ametys.plugins.contentio.ImportActions', {
    singleton: true,
    
    /**
	 * Import contents from server directory
	 * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
	 */
    importDir: function (controller)
    {
    	var target = controller.getMatchingTargets()[0];
    	if (target != null)
    	{
    		this._delayedInitialize();
    		
    		this._box.down("#parentId").setValue(target.getParameters().id);
    		this._box.show();
    	}
    },
    
    /**
     * @private
     * Creates the dialog box
     */
    _delayedInitialize: function ()
    {
    	if (!this._initialized)
    	{
    		this._box = Ext.create('Ametys.window.DialogBox', {
                title: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_DIALOG_TITLE}}",
                iconCls:'ametysicon-documents12',
                width: 550,
                scrollable: false,
                
                layout: {
                    type: 'vbox',
                    align : 'stretch',
                    pack  : 'start'
                },
                
                items: [{
    	                xtype: 'component',
    	                cls: 'a-text',
    	                html: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_HINT_1}}"
    	            },
    	            {
    	                xtype: 'hidden',
    	                name: 'parentId',
    	                itemId: 'parentId'
    	            },
    	            {
    	                xtype: 'textfield',
    	                labelWidth: 120,
    	                msgTarget: 'side',
    	                itemId: 'path',
    	                name: 'path',
    	                allowBlank: false,
    	                fieldLabel: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_PATH}}",
    	                ametysDescription: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_PATH_DESC}}"
    	            },
    	            {
    	                xtype: 'component',
    	                cls: 'a-text',
    	                html: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_HINT_2}}"
    	            }
    	        ],
                
                referenceHolder: true,
                defaultButton: 'validate',
                
                closeAction: 'hide',
                buttons : [{
                    	reference: 'validate',
                        itemId: 'validate-btn',
                        text :"{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_DIALOG_OK_BTN}}",
                        handler: this._validate,
                        scope: this
                    },
                    {
                        text :"{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_DIALOG_CANCEL_BTN}}",
                        handler: function () {this._box.close()},
                        scope: this
                    } 
                ]
            });
    		
    		this._initialized = true;
    	}
    },
    
    /**
     * @private
     * Handler invoked when clicking on 'Ok' button of the dialog box
     */
    _validate: function ()
    {
    	var fieldPath = this._box.down("#path");
    	if (!fieldPath.isValid())
    	{
    		return;
    	}
    	
    	Ametys.data.ServerComm.callMethod({
			role: "org.ametys.plugins.webcontentio.ContentIOManager",
			methodName: "importContent",
			parameters: [this._box.down("#path").getValue(), this._box.down("#parentId").getValue()],
			callback: {
				scope: this,
				handler: this._importCb,
				arguments: [this._box.down("#parentId").getValue()]
			},
			errorMessage: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_ERROR}}",
			waitMessage: "{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_WAIT}}"
		});
    },
    
    /**
     * @private
     * Callback function invoked after importing contents
     * @param {Object} result The server response
     * @param {Object[]} args The transmitted arguments
     * @param {String} args.0 The page identifier
     */
    _importCb: function (result, args)
    {
    	this._box.hide();
    	
    	var msg = result.success + " {{i18n PLUGINS_WEB_CONTENTIO_IMPORT_RESULT_SUCCESS}}";
    	if (result.error > 0)
    	{
    		msg += "<br/>" + result.error + " {{i18n PLUGINS_WEB_CONTENTIO_IMPORT_RESULT_ERROR}}";
    	}
    	
    	Ametys.Msg.show({
    		   title:"{{i18n PLUGINS_WEB_CONTENTIO_IMPORT_RESULT_TITLE}}",
    		   msg: msg,
    		   buttons: Ext.Msg.OK,
    		   icon: result.error == 0 ? Ext.MessageBox.INFO : Ext.MessageBox.WARNING
    	});
    	
    	if (result.success > 0)
    	{
    		// FIXME we need to releoa parent page
    		Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.PAGE,
                    parameters: { 
                        ids: [args[0]]
                    }
                }
            });
        }
    }
    	
});