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

/**
 * Dialog to import a list of tags from an xml file
 */
Ext.define("Ametys.plugins.cms.tag.ImportTagsUI", {
	
	singleton: true,
	
	/**
	 * @private
	 * @property {Function} _cbFn Callback function to execute after import
	 */
	
	/**
	 * Open the dialog box for import
	 * @param {String} parentId (required) The id of parent tag
	 * @param {String} tagProvider The provider of tags. Can be null to use the default tag provider.
	 * @param {Function} callback The function to call in case of success
	 */
	open: function (parentId, tagProvider, callback)
	{
		this._cbFn = callback;
		
		this._delayedInitialize();
		
		this._initForm (parentId, tagProvider);
		this._box.show();
	},
	
	/**
	 * @private
	 * Creates the dialog box
	 */
	_delayedInitialize: function ()
	{
		if (this._initialized)
			return;
		
		this._formPanel = this._createFormPanel();
		
		this._box = Ext.create('Ametys.window.DialogBox', {
			title: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_TITLE}}",
            iconCls: 'ametysicon-upload119',
            
            width: 520,
            scrollable: false,
            
            items: [this._formPanel],

            closeAction: 'hide',
            buttons: [{
                text: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_BUTTON_OK}}",
                handler: Ext.bind(this._validate, this)
            }, {
                text: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_BUTTON_CANCEL}}",
                handler: Ext.bind(this._cancel, this)
            }]    
		});
		
		this._initialized = true;
	},
	
	/**
	 * @private
	 * Initialize the form
	 * @param {String} parentId (required) The id of parent tag
	 * @param {String} [tagProvider] The provider of tags. Can be null to use the default tag provider.
	 */
	_initForm: function (parentId, tagProvider)
	{
		var form = this._formPanel.getForm();
	    form.findField('tagId').setValue(parentId);
	    form.findField('tagProvider').setValue(tagProvider);
	    form.findField('importFile').reset();
	},

   /**
    * @private
    * Handler for the 'ok' button of the dialog box
    */
    _validate: function ()
    {
        var form = this._formPanel.getForm();
        if (!form.isValid())
        {
        	return;
        }
        
        // Submit form
        form.submit({
        	url: Ametys.getPluginDirectPrefix("cms") + '/tags/import',
            params: {contextualParameters: Ext.JSON.encode(Ametys.getAppParameters())},
            
            waitTitle: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_WAIT_TITLE}}",
            waitMsg: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_WAIT_MSG}}",
            
            success: Ext.bind(this._importSuccess, this),
            failure: this._importFailure,
            
            errorReader: new Ext.data.XmlReader({
                record: 'field',
                success: '@success'
            })
        });
    },
    
    /**
     * @private
     * Callback for the "cancel" button of the dialog. Close the dialog.
     */
    _cancel: function ()
    {
        this._box.close();
    },
    
    /**
     * @private
     * Callback invoked after successful import
     * @param {HTMLElement} form The form submitted
     * @param {Object} action The result action
     */
    _importSuccess: function (form, action)
    {
    	var message = "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_SUCCESS_START}}";
    	if (action.result.createdCount == 1)
    	{
    		message += "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_CREATE_TAG_SUCCESS}}";
    	}
    	else if (action.result.createdCount > 1)
    	{
    	    message += action.result.createdCount + "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_CREATE_TAGS_SUCCESS}}";
    	}
    	
    	if (action.result.updatedCount == 1)
    	{
    	    message += "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_UPDATE_TAG_SUCCESS}}";
    	}
    	else if (action.result.updatedCount > 1)
    	{
    	    message += action.result.updatedCount + "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_UPDATE_TAGS_SUCCESS}}";
    	}
    	
    	if (action.result.errorCount == 1)
    	{
    	    message += "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_TAG_ERROR}}";
    	}
    	else if (action.result.errorCount > 1)
    	{
    	    message += action.result.errorCount + "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_TAGS_ERROR}}";
    	}
    	
    	Ametys.Msg.show({
    	    title: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_SUCCESS_TITLE}}",
    	    msg: message,
    	    buttons: Ext.Msg.OK,
    	    icon: Ext.MessageBox.INFO
    	});
    	
    	this._box.close();
    	this._cbFn ();
    },
    
    /**
     * Callback invoked after failing to import
     * @param {HTMLElement} form The form submitted
     * @param {Object} action The result action
     */
    _importFailure: function(form, action)
    {
    	var message = '';
    	var error = action.result.error;
    	
    	if (error == 'invalid-extension')
    	{
    	    message = "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_ERROR_INVALID_FILE}}";
    	}
    	else if (error == 'rejected-file')
    	{
    	    message = "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_ERROR_REJECTED_FILE}}";
    	}
    	else if (error == 'id-not-match')
    	{
    	    message = "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_ERROR_ID_DOESNOT_MATCH}}";
    	}
    	else
    	{
    	    message = "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_ERROR}}";
    	}
    	
    	Ametys.Msg.show({
    	    title: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_ERROR_TITLE}}",
    	    msg: message,
    	    buttons: Ext.Msg.OK,
    	    icon: Ext.MessageBox.ERROR
    	});
    },

    /**
     * @private
     * Create the form panel
     * @return {Ext.form.FormPanel} the form panel
     */
    _createFormPanel: function()
    {
        var formPanel = new Ext.form.FormPanel( {
            labelWidth: 80,
            defaultType: 'textfield',
            fileUpload: true,
            
            defaults: {
                cls: 'ametys',
                labelAlign: 'right',
                labelSeparator: '',
                labelWidth: 80,
                width: 470
            },
            
            items: [
                {
                    xtype: 'hidden',
                    name: 'tagId'
                },
                {
                    xtype: 'hidden',
                    name: 'tagProvider'
                },
                {
                    xtype: 'component',
                    html: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_HINT}}",
                    cls: 'a-text'
                },
                {
                    xtype: 'filefield',
                    name: 'importFile',
                    fieldLabel: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_FILE_LABEL}} *",
                    ametysDescription: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_FILE_DESC}}",
                    allowBlank: false,
                    emptyText: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_FILE_EMPTY_TEXT}}",
                    buttonText: "{{i18n PLUGINS_CMS_HANDLE_TAGS_IMPORT_XML_DIALOG_FILE_BUTTON}}"
                }
            ],
            
            border: false,
            scrollable: true
        });
        
        return formPanel;
    }
});