'use strict';

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Licensed Materials - Property of IBM
 * IBM Cognos Products: BI Cloud (C) Copyright IBM Corp. 2019, 2020
 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */
define(['../../../../app/nls/StringResources', '../../../../lib/@waca/dashboard-common/dist/ui/interaction/Utils', 'jquery', 'underscore', '../../../../lib/@waca/dashboard-common/dist/core/APIFactory', '../../../../lib/@waca/dashboard-common/dist/api/ContentActionsProviderAPI'], function (stringResources, Utils, $, _, APIFactory, ContentActionsProviderAPI) {
	var DuplicateAction = function () {
		function DuplicateAction(_ref) {
			var features = _ref.features;

			_classCallCheck(this, DuplicateAction);

			if (features) {
				this.dashboard = features.API;
				features.ContentActions.registerProvider('duplicate', this.getAPI());
				this._dashboardState = features.DashboardState;
				this._icons = features.Icons;
			}
		}

		DuplicateAction.prototype.getAPI = function getAPI() {
			if (!this._api) {
				this._api = APIFactory.createAPI(this, [ContentActionsProviderAPI]);
			}
			return this._api;
		};

		DuplicateAction.prototype.getLifeCycleHandlers = function getLifeCycleHandlers() {
			return [{
				name: 'post:dashboard.initialize',
				action: this.postDashboardInitialize.bind(this)
			}];
		};

		DuplicateAction.prototype.postDashboardInitialize = function postDashboardInitialize() {
			if (this.dashboard) {
				this.controller = this.dashboard.getFeature('InteractionController.internal');
			}
			return Promise.resolve();
		};

		DuplicateAction.prototype.destroy = function destroy() {
			this.dashboard = null;
			this.controller = null;
		};

		DuplicateAction.prototype.getNodes = function getNodes(idList) {
			return Utils.getNodes(this.controller, idList);
		};

		DuplicateAction.prototype._isAvailable = function _isAvailable(idList) {
			// Make sure duplicate action is not available for filter widget
			return idList.length && this._isSupportedVisualizations(idList) && this.dashboard.getMode() === this.dashboard.MODES.EDIT && _.find(this.getNodes(idList), function (n) {
				return $(n).hasClass('filterWidget');
			}) === undefined;
		};

		DuplicateAction.prototype._isSupportedVisualizations = function _isSupportedVisualizations(idList) {
			for (var index = 0; index < idList.length; index++) {
				if (this._isNotSupportedVisualization(idList[index])) {
					return false;
				}
			}
			return true;
		};

		DuplicateAction.prototype._isNotSupportedVisualization = function _isNotSupportedVisualization(id) {
			var content = this.dashboard.getCanvas().getContent(id);
			if (!content) {
				return false;
			}

			var visualization = content.getFeature('Visualization');

			return content.getType() === 'widget.live' && visualization && visualization.getDefinition().getId() === 'com.ibm.vis.schematicsPreview';
		};

		DuplicateAction.prototype._isDisabled = function _isDisabled() {
			return this._dashboardState.getUiState().focus;
		};

		DuplicateAction.prototype.getContentActionList = function getContentActionList(idList) {
			if (this._isAvailable(idList)) {
				return [{
					name: 'duplicate',
					label: stringResources.get('duplicate'),
					icon: this._icons.getIcon('dashboard-duplicate').id,
					type: 'Button',
					disabled: this._isDisabled.bind(this),
					actions: {
						apply: this.duplicateContent.bind(this, idList)
					}
				}];
			}
			return [];
		};

		/**
   * Duplicate the selected items for the board layout
   * @param {String[]} idList Array of model id list.
   */


		DuplicateAction.prototype.duplicateContent = function duplicateContent(idList, evt) {
			var _this = this;

			var modelIds = [];
			var outBoundIds = [];
			//Get view port bounds
			var viewPortView = this.controller.layoutController.getLayoutContentContainer();
			_.each(this.getNodes(idList), function (node) {
				var modelId = this.controller.layoutController.nodeIdToModelId(node.id);
				var bounds = this._checkLayoutBoundLimits(node, viewPortView);
				if (!bounds.right || !bounds.bottom) {
					outBoundIds.push({ 'id': modelId, 'right': bounds.right, 'bottom': bounds.bottom });
				}
				modelIds.push(modelId);
			}.bind(this));
			var options = {
				modelIds: modelIds
			};
			if (outBoundIds.length > 0) {
				options.outBoundIds = outBoundIds;
			}
			var duplicatedIdsPromise = this.controller.boardModel.duplicateSelection(options);
			this.controller.selectionHandler.deselectAll();
			var returnedPromise = [];
			duplicatedIdsPromise.forEach(function (duplicatedIdPromise) {
				return returnedPromise.push(duplicatedIdPromise.then(function (duplicatedId) {
					return _this.controller.layoutController.selectLayouts([duplicatedId], evt);
				}).catch(function (err) {
					console.log(err);
				}));
			});
			return returnedPromise;
		};

		/**
   * Check if duplicate item will fall out of bound of the current consume view
   * Only applies for Guided Journey layouts
   */

		DuplicateAction.prototype._checkLayoutBoundLimits = function _checkLayoutBoundLimits(node, viewPort) {
			var shouldExpand = { right: true, bottom: true };
			/* Get current consume view bounds */
			var consumViewMaxHeight = node._layout.parentLayout.getMaximumHeight();
			var consumViewMaxWidth = node._layout.parentLayout.getMaximumWidth();
			/* Only in GJ will the numbers being finite*/
			if (isFinite(consumViewMaxHeight) && isFinite(consumViewMaxWidth)) {
				/* Get the view port bounds */
				var viewPortMaxHeight = viewPort.clientHeight;
				var viewPortMaxWidth = viewPort.clientWidth;
				/* Should be finite. Check just in case */
				if (isFinite(viewPortMaxHeight) && isFinite(viewPortMaxWidth)) {
					/* Get the styles from layout model for this widget */
					var layOutModel = node._layout.model;
					var style = layOutModel.style;
					if (style) {
						/*
       * Calculate the bounds based on a 5% down/right move of the current node
       * The style contains % of the view port space, not the consume view
       */
						var expectedTop = parseFloat(layOutModel.incrementStyleValue(style.top)) / 100 * viewPortMaxHeight;
						var expectedLeft = parseFloat(layOutModel.incrementStyleValue(style.left)) / 100 * viewPortMaxWidth;
						/* Height and Width of this object */
						var objHeight = parseFloat(style.height) / 100 * viewPortMaxHeight;
						var objWidth = parseFloat(style.width) / 100 * viewPortMaxWidth;
						if (expectedTop + objHeight > consumViewMaxHeight) {
							shouldExpand.bottom = false;
						}
						if (expectedLeft + objWidth > consumViewMaxWidth) {
							shouldExpand.right = false;
						}
					}
				}
			}
			return shouldExpand;
		};

		return DuplicateAction;
	}();

	return DuplicateAction;
});
//# sourceMappingURL=DuplicateAction.js.map