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

/**
 * @private
 * UI helper to flag translation on a page. See #open method.
 */
Ext.define("Ametys.plugins.translationflagging.TranslationHelper", {
	singleton: true,
	
	/**
	 * Open dialog box to select flag translations on a page
	 * @param {Object} config The configuration object
	 * @param {String} config.id (required) The ID of page to flag
	 * @param {String} config.title (required) The page's title
	 * @param {String} config.lang (required) The page's language
	 * @param {Object[]} config.translations The current translations of the page : [{lang: 'fr', id: 'page1'}, {lang: 'en', id: 'page2'}, ..]
	 * @param {Function} config.callback Callback function to call when validating dialog box
	 * @param {String} config.callback.id The page's id
	 * @param {Object} config.callback.translations The selected translations such as {'fr': page1, 'en': page2, ....}
	 */
	open: function (config)
	{
		this._cbFn = config.callback;
		
		this._createDialog(config);
		this._initForm(config.translations);
		
		this._box.show();
	},
	
	/**
	 * Creates the dialog box
	 * @param {Object} config The configuration object
	 * @private
	 */
	_createDialog: function (config)
    {
		var items = [
			{
				xtype: 'component',
				cls: 'a-text',
				html: "{{i18n PLUGINS_TRANSLATIONFLAGGING_DIALOG_HELP_TEXT_1}}" + Ext.String.escapeHtml(config.title) + "{{i18n PLUGINS_TRANSLATIONFLAGGING_DIALOG_HELP_TEXT_2}}"
			}, 
			{
			    xtype: 'hidden',
			    name: 'id',
			    value: config.id
			}
		];
		
		var langStore = Ametys.cms.language.LanguageDAO.getStore();
        var firstLang;
        
    	langStore.getData().each (function (lang) {
    		
    		if (lang.getName() != config.lang)
    		{
                if (!firstLang) firstLang = lang.getName();
                
    			items.push({
                    xtype: 'edition.select-page',
                    
                    siteContext: Ametys.web.form.widget.SelectPage.SITE_CONTEXT_CURRENT,
                    sitemapContext: lang.getName(),
                    multiple: false,
                    
                    itemId: 'select-page-' + lang.getName(),
                    name: lang.getName(),
                    fieldLabel: lang.getLabel(),
                    ametysDescription: "{{i18n PLUGINS_TRANSLATIONFLAGGING_DIALOG_PAGE_DESC}}" + lang.getLabel(),
                    
                    allowCreation: true
                });
    		}
    	});
		
		this._box = Ext.create('Ametys.window.DialogBox', {
			title: "{{i18n PLUGINS_TRANSLATIONFLAGGING_DIALOG_TITLE}}",
            iconCls: 'ametysicon-translation',
			
            width: 490,
            maxHeight: 500,
			
			items: [{
						xtype: 'form',
						border: false,
						scrollable: true,
						defaults: {
							cls: 'ametys',
							labelAlign: 'right',
							labelSeparator: '',
							width: 400
						},
						items: items
					}
			],
			
			closeAction: 'destroy',
			defaultFocus: 'select-page-' + firstLang,
			
			referenceHolder: true,
			defaultButton: 'validate',
			
			buttons: [{
				reference: 'validate',
                text: "{{i18n PLUGINS_TRANSLATIONFLAGGING_DIALOG_BUTTON_OK}}",
                handler: Ext.bind(this._validate, this)
            }, {
                text: "{{i18n PLUGINS_TRANSLATIONFLAGGING_DIALOG_BUTTON_CANCEL}}",
                handler: Ext.bind(function() {this._box.hide();}, this) 
            }]  
		});
    },
    
    /**
     * @private
     * Initialize the form
     * @param {Object[]} translations The current translations of the page
     */
    _initForm: function (translations)
    {
    	var form = this._box.items.get(0).getForm();
    	
    	Ext.Array.forEach (translations, function (translation) {
    		var pageFd = form.findField(translation.lang);
    		if (pageFd != null)
    		{
    			pageFd.setValue(translation.id);
    		}
    	});
    },
    
    /**
     * @private
     * Handler when 'Ok' button is clicked.
     * Execute the callback function with the selected pages.
     */
    _validate: function ()
    {
    	var form = this._box.items.get(0).getForm();
    	var values = form.getValues();
    	
    	var id = values.id;
    	delete values.id;
    	
    	if (Ext.isFunction (this._cbFn))
    	{
    		this._cbFn (id, values);
    	}
    	
    	this._box.hide();
    }
       
});