/*
 *  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 class is a singleton to handle actions concerning user population in a web context.
 */
Ext.define('Ametys.plugins.web.populations.PopulationActions', {
    singleton: true, 
    
    /**
     * @property {String} _contextBO The context for BO populations
     * @private
     */
    /**
     * @property {String} _contextFO The context for FO populations
     * @private
     */
    /**
     * @property {String} _hintText The hint text in the dialog box
     * @private
     */
    /**
     * @property {Function} _callback The callback function
     * @private
     */
    /**
     * @property {String[]} _populationsBO The ids of the BO populations
     * @private
     */
    /**
     * @private
     * @property {String} _currentSiteName The current site name
     */
    /**
     * @private
     * @property {String} _currentSiteId The current site id
     */
    
    /**
     * Opens a dialog box to select the user populations to link to the selected site context (BO and FO)
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    linkToSite: function(controller)
    {
        var targets = controller.getMatchingTargets();
        
        if (targets.length > 0)
        {
            var siteId = targets[0].getParameters().id;
            var siteName = targets[0].getParameters().name;
            var siteTitle = targets[0].getParameters().title || siteName;
            
            var contextBO = controller.getInitialConfig('contextBO') + '/' + siteName;
            var contextFO = controller.getInitialConfig('contextFO') + '/' + siteName;
            
            this.openLinkToSiteDialog(contextBO, contextFO, siteId, siteName, siteTitle);
        }
    },
    
    /**
     * Opens a dialog box to select the user populations to link to the selected site context (BO and FO)
     * @param {String} contextBO The BO context
     * @param {String} contextFO The FO context
     * @param {String} siteId The id of the site
     * @param {String} siteName The name of the site
     * @param {String} siteTitle The title of the site
     */
    openLinkToSiteDialog: function(contextBO, contextFO, siteId, siteName, siteTitle)
    {
        this._contextBO = contextBO;
        this._contextFO = contextFO;
        this._currentSiteId = siteId;
        this._currentSiteName = siteName;
        
        this._hintText = Ext.String.format("{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HINT}}", siteTitle || siteName);
        
        this._callback = Ext.bind(this._sendModifiedSiteMsg, this, [siteId, siteName], 1);
        
        Ametys.plugins.core.populations.UserPopulationDAO.getUserPopulationsOnContexts([[this._contextBO], true], this._linkToContexts, {scope: this});
    },
    
    /**
     * @private
     * Retrieve the already linked populations on the second context(FO) after retrieving the ones on the first context (BO)
     * @param {String[]} populationsBO The populations linked to the first context (BO)
     */
    _linkToContexts: function(populationsBO)
    {
        this._populationsBO = populationsBO;
        Ametys.plugins.core.populations.UserPopulationDAO.getUserPopulationsOnContexts([[this._contextFO], true], this._openChooseDialog, {scope: this});
    },
    
    /**
     * @private
     * Function to open the choose dialog box
     * @param {String[]} populationsFO The ids of the already linked user populations of FO
     */
    _openChooseDialog: function(populationsFO)
    {
        Ametys.plugins.web.populations.ChooseUserPopulationsHelper.open({
            title: "{{i18n plugin.core-ui:PLUGINS_CORE_UI_USER_POPULATIONS_CHOOSE_POPULATIONS_TITLE}}",
            hintText: this._hintText,
            selectedIds1: this._populationsBO,
            selectedIds2: populationsFO,
            allowCreation: true,
            okAction: Ext.bind(this._doLinkPopulations, this)
        });
    },
    
    /**
     * @private
     * Sends a modified message bus on the site if needed.
     * @param {Object} response The server response
     * @param {String} siteId The id of the site
     * @param {String} siteName The name of the site
     */
    _sendModifiedSiteMsg: function(response, siteId, siteName)
    {
        if (response != null) //  Response length can be empty that will notify no added, no removed, but it not does not imply that order have not changed
        {
            Ext.create('Ametys.message.Message', {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.SITE,
                    parameters: {
                        id: siteId,
                        name: siteName
                    }
                }
            });
        }
    },
    
    /**
     * @private
     * Links some user populations to 2 context
     * @param {String[]} idsBO The ids of the selected user populations for BO
     * @param {String[]} idsFO The ids of the selected user populations for FO
     */
    _doLinkPopulations: function(idsBO, idsFO)
    {
        Ametys.plugins.core.populations.UserPopulationDAO.link([this._contextBO, idsBO], this._callback || Ext.emptyFn, {scope: this});
        Ametys.plugins.core.populations.UserPopulationDAO.link([this._contextFO, idsFO], this._callback || Ext.emptyFn, {scope: this});
        
        Ametys.notify({
            type: 'info',
            iconGlyph: 'ametysicon-multiple25',
            title: "{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_DONE_TITLE}}",
            description: Ext.String.format("{{i18n PLUGINS_WEB_USER_POPULATIONS_CHOOSE_POPULATIONS_HELPER_DONE_DESC}}", this._currentSiteName),
            action: Ext.bind(Ametys.tool.ToolsManager.openTool, Ametys.tool.ToolsManager, ['uitool-admin-sites', {id: this._currentSiteId}], false)
        });
    }
});