/*
 *  Copyright 2024 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 controls a ribbon button to paste a service
 * @private
 */
Ext.define('Ametys.plugins.web.page.controller.PasteServiceController', {
	extend: 'Ametys.web.controller.WebButtonController',
	
	constructor: function(config)
	{
		this.callParent(arguments);
		Ametys.message.MessageBus.on(Ametys.message.Message.MODIFIED, this._onMessageModified, this);
	},
	
	_onMessageModified: function(message)
	{
		if (this.updateTargetsInCurrentSelectionTargets (message))
        {
            this.refresh();
        }
	},
	
	updateState: function()
	{
		this._getStatus(this.getMatchingTargets());
	},
	
	areSameTargets: function(target1, target2)
	{
		var match = this.callParent(arguments);
		return match && target1.getParameters()['zone-name'] == target2.getParameters()['zone-name'];
	},
	
	/**
	 * Get the status of current matching zone-item
	 * @param {Ametys.message.MessageTarget[]} targets The matching targets
	 */
	_getStatus: function (targets)
	{
		this.disable();
		
		if (targets.length > 0)
		{
			var clipboardData = Ametys.clipboard.Clipboard.getData();
			if (clipboardData.length > 0 && Ametys.clipboard.Clipboard.getType() == Ametys.message.MessageTarget.ZONE_ITEM && clipboardData[0].service)
			{
				var serviceId = clipboardData[0].service;
				var pageId = targets[0].getParameters().id;
				var zoneName = targets[0].getParameters()['zone-name'];
				
				Ametys.web.page.PageDAO.getAvailableServices([pageId, zoneName], Ext.bind(this._getStatusCb, this, [serviceId], 1));
			}
			else
			{
				this.setAdditionalDescription(this.getInitialConfig('empty-clipboard-description'));
			}
		}
	},
	
	/**
	 * @private
	 * Callback function called after retrieving the available services
	 * @param {Object[]} availableServices the list of available services 
	 */
	_getStatusCb: function (availableServices, serviceId)
	{
        var availableServiceIds = Ext.Array.map(availableServices, s => s.id);
        if (Ext.Array.contains(availableServiceIds, serviceId))
        {
            this.enable();
        }
        else
        {
            this.setAdditionalDescription(this.getInitialConfig('noservice-description'));
        }
	}
});