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

/**
 * Singleton class for skills actions.
 * @private
 */
Ext.define('Ametys.plugins.odf.skills.SkillsActions', {
    singleton: true,
    
    /**
     * Action function to be called by the controller.
     * Will delete the contents registered by the controller.
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    delete: function (controller)
    {
        var contentIds = controller.getContentIds();
        if (contentIds.length > 0)
        {
            var contentTitles = this._getContentTitles(controller, contentIds);
            
            Ametys.Msg.confirm("{{i18n PLUGINS_ODF_CONTENT_DELETE_LABEL}}", 
                    Ext.String.format("{{i18n SKILL_DELETE_CONFIRM}}", contentTitles.join(', ')),
                    Ext.bind(this._deleteConfirm, this, [controller, contentIds], 1),
                    this
            );
        }
    },
        
    /**
     * Get the content titles from the matching targets
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the #act function
     * @param {String[]} contentIds The content identifiers
     */
    _getContentTitles: function (controller, contentIds)
    {
        var contentTitles = [];

        var contentTargets = controller.getMatchingTargets();
        Ext.Array.forEach (contentTargets, function (contentTarget) {
            if (Ext.Array.contains (contentIds, contentTarget.getParameters().id))
            {
                contentTitles.push (contentTarget.getParameters().title);
            }
        });
        
        return contentTitles;
    },
        
    /**
     * Callback function invoked after the #act confirm box is closed
     * @param {String} answer Id of the button that was clicked
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling the #act function
     * @param {String[]} contentIds The content identifiers
     * @private
     */
    _deleteConfirm: function (answer, controller, contentIds)
    {
        if (answer == 'yes')
        {
            Ametys.cms.content.ContentDAO.forceTrashContents (contentIds, controller.getMatchingTargets());
        }
    },
    
    /**
     * Exclude or include program items
     * @param {Ametys.ribbon.element.ui.ButtonController} controller the controller calling this function
     * @param {Boolean} state the press-state of the controller
     */
    setProgramItemsExclusion: function (controller, state)
    {
        var excluded = state;
		var allowedContentIds = controller.getContentIds();
        var contentIds = excluded ? controller.getIncludedProgramItemIds() : controller.getExcludedProgramItemIds();
        contentIds = Ext.Array.filter(contentIds, id => Ext.Array.contains(allowedContentIds, id));
		
        Ametys.data.ServerComm.callMethod({
            role: "org.ametys.odf.skill.ODFSkillsHelper",
            methodName: "setProgramItemsExclusion",
            parameters: [contentIds, excluded],
            callback: {
                handler: this._setProgramItemsExclusionCB,
                scope: this,
                arguments: []
            },
            errorMessage:true,
            waitMessage: true
        });
    },
    
    /**
     * Callback function after excluding or including the program items
     * @param {Object} response The server response
     */
    _setProgramItemsExclusionCB: function (response)
    {
        var programItems = response["allright-program-items"];
        if (programItems != null && programItems.length > 0)
        {
            var ids = [];
            for (var i = 0; i < programItems.length; i++) 
            {
                ids.push(programItems[i].id);
            }

            Ext.create("Ametys.message.Message", {
                type: Ametys.message.Message.MODIFIED,
                targets: {
                    id: Ametys.message.MessageTarget.CONTENT,
                    parameters: { 
                        ids: ids
                    }
                }
            });
        }
		
		var noRightProgramItems = response["noright-program-items"];
		var warnMsg = "";
        if (noRightProgramItems.length > 0)
        {
			var noRightProgramItemTitles = Ext.Array.map(noRightProgramItems,  pi => pi.title).join(", ");
			var warnMsg = Ext.String.format("{{i18n PLUGINS_ODF_PROGRAM_ITEM_SKILLS_EXCLUDED_NORIGHT_WARN}}", noRightProgramItemTitles);
			
			Ametys.notify({
	            type: 'warn',
	            iconGlyph: 'ametysicon-visibility',
	            title: "{{i18n PLUGINS_ODF_PROGRAM_ITEM_SKILLS_EXCLUSION_LABEL}}",
	            description: warnMsg
	        });
        }
    }
});