/*
 *  Copyright 2016 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 is like the runtime one for choosing user populations for two contexts.
 * See {@link Ametys.plugins.coreui.populations.ChooseUserPopulationsHelper}
 */
Ext.define('Ametys.plugins.web.populations.ChooseUserPopulationsHelper', {
    singleton: true,
    
    /**
     * Opens a dialog box helper for choosing one or more user populations.
     * @param {Object} config The configuration object
     * @param {String} config.title The title of the dialog box
     * @param {String} config.hintText The text of the hint.
     * @param {Function} config.okAction The action to perform when clicking on the 'ok' button
     * @param {String[]} [config.selectedIds1] The ids of the populations which have to be selected at opening in first field
     * @param {String[]} [config.selectedIds2] The ids of the populations which have to be selected at opening in second field
     * @param {Boolean} [config.allowCreation=false] Set tot true to allow population creation
     */
    open: function(config)
    {
        var commonCfg = {
            multiple: true,
            allowCreation: config.allowCreation,
            
            cls: 'ametys',
            style: "margin-top: 10px;",
            labelSeparator: '',
            labelAlign: 'top',
            labelWidth: 200,
            width: '100%',
            msgTarget: 'side'
        };
        
        var selectPopulationsWidget1 = Ext.create('Ametys.form.widget.UserPopulation', Ext.apply({
            itemId: 'select-populations-widget1',
            fieldLabel: "<b>{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_BO_POPULATIONS_LABEL}}</b>",
            ametysDescription: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_BO_POPULATIONS_DESCRIPTION}}",
            value: config.selectedIds1 || [],
            showDisabled: true
        }, commonCfg));
        var selectPopulationsWidget2 = Ext.create('Ametys.form.widget.UserPopulation', Ext.apply({
            itemId: 'select-populations-widget2',
            fieldLabel: "<b>{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_POPULATIONS_LABEL}}</b>",
            ametysDescription: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_POPULATIONS_DESCRIPTION}}",
            value: config.selectedIds2 || [],
            showDisabled: true
        }, commonCfg));
        
        this._box = Ext.create('Ametys.window.DialogBox', {
            title: config.title || '',
            iconCls: 'ametysicon-multiple25',
            
            layout: {
                type: "vbox",
                align: "stretch"
            },
            width: 500,
            scrollable: true,
            
            closeAction: 'destroy',
            items: [
                {
                    xtype: "component",
                    html: config.hintText || ''
                }, 
                selectPopulationsWidget1,
                selectPopulationsWidget2
            ],
            
            referenceHolder: true,
            defaultButton: 'buttonOk',
            buttons: [{
                itemId: 'button-ok',
                reference: 'buttonOk',
                text: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_OK_BUTTON}}",
                handler: Ext.bind(this._validate, this, [config.okAction]),
                scope: this
            }, {
                itemId: 'button-cancel',
                text: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_CANCEL_BUTTON}}",
                handler: function() {this._box.close();},
                scope: this
            }]
        });
        
        this._box.show();
    },
    
    /**
     * @private
     * Action to perform when the 'ok' button is clicked
     * @param {Function} callback The function to call
     */
    _validate: function(callback)
    {
        var me = this;
        var ids1 = me._box.items.get('select-populations-widget1').getValue();
        var ids2 = me._box.items.get('select-populations-widget2').getValue();
        
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.core.observation.ObserverExtensionPoint",
            id: "org.ametys.web.cache.SynchronizeUserPopulationsObserver",
            methodName: "testFrontOfficesDatasources",
            parameters: [
                Ext.Array.merge(ids1, ids2)
            ],
            callback: {
                handler: function(errors) { 
                    function finish()
                    {
                        if (Ext.isFunction(callback))
                        {
                            callback(ids1, ids2);
                        }
                        
                        me._box.close();
                    }
                    
                    if (errors)
                    {
                        var msg = "<ul>";
                        Ext.Object.each(errors, function (key, value) {
                            msg += "<li><b>{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_TEXT2}} '" + key + "'</b><ul>"
                            Ext.Object.each(value, function (subkey, subvalue) {
                                msg += "<li>{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_TEXT3}} '<b>" + subvalue.label + "</b> (" + subkey + ")'<br/>" + subvalue.error + "</li>";
                            });
                            msg += "</ul></li>";
                        });
                        msg += "</ul>{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_TEXT4}}"
                        
                        Ametys.Msg.show({ 
                            title: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_TEXT0}}", 
                            message: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_TEXT1}}" + msg,
                            icon: Ext.Msg.WARNING,
                            buttons: Ext.Msg.YESNO,
                            callback: function(btn)
                            {
                                if (btn == 'yes')
                                {
                                    finish();
                                }
                            }
                        });
                    }
                    else
                    {
                        finish();
                    }
                },
                ignoreOnError: false
            },
            waitMessage: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_WAIT}}",
            errorMessage: { msg: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_FO_TEST_ERROR}}" }
        });         
    }
});