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

/**
 * Actions to change the privacy of the current selection
 * @private
 */
Ext.define('Ametys.plugins.web.content.ContentActions',
{
    singleton: true,

    /**
     * Set the privacy level of the selected contents
     * @param {Ametys.ribbon.element.ui.ButtonController} controller The controller calling this function
     */
    setPrivacy: function (controller)
    {
        var parentControllerId = controller['parent-controller'];
        var parentController = Ametys.ribbon.RibbonManager.getUI(parentControllerId);
        
        var contentIds = parentController.getContentIds();
		if (contentIds.length > 0)
		{
			var privacyLevel = controller.getInitialConfig().privacyLevel;
			parentController.serverCall('updatePrivacy', [contentIds, privacyLevel], this._setPrivacyCb, {
                errorMessage:
                {
                    msg: "{{i18n PLUGINS_WEB_CONTENT_PRIVACY_UPDATE_ERROR}}",
                    waitMessage: true
                }
            });
		}
    },

    /**
     * Callback for the {#setPrivacy} Method.
     * @param {Object[]} response The server response
     * @private
     */
    _setPrivacyCb: function (response)
    {
        var ids = response["allright-contents"] || [];
        if (ids.length)
        {
            Ext.create("Ametys.message.Message",
	        {
	            type: Ametys.message.Message.MODIFIED,
	            targets:
	            {
	                id: Ametys.message.MessageTarget.CONTENT,
	                parameters:
	                {
	                    ids: ids
	                }
	            }
	        });
        }
        
        var noRightContents = response["noright-contents"] || [];
        if (noRightContents.length)
        {
            var msg = errorMsg;
            msg += Ext.Array.map(noRightContents, c => c.title).join(", ");
            
            Ametys.Msg.show({
                title: errorTitle,
                msg: msg,
                buttons: Ext.Msg.OK,
                icon: Ext.MessageBox.ERROR
            });
        }
    }
});