'use strict';

const inArray = require("in-array");

function findContainer(tag) {
	let lastTag = tag;
	let dockableContainer;

	while (dockableContainer == null && lastTag != null) {
		let candidate = lastTag.parent;

		if (candidate != null && candidate._uikitDockableContainer != null && candidate._uikitDockableContainer.isActive()) {
			dockableContainer = candidate;
		} else {
			lastTag = candidate;
		}
	}

	if (dockableContainer != null) {
		return dockableContainer;
	} else {
		// FIXME: Better error reporting?
		throw new Error("Could not find a dockable container for tag");
	}
}

module.exports = {
	init: function() {
		if (this.opts.dock != null) {
			let dockableContainer = findContainer(this);
			let containerData = dockableContainer._uikitDockableContainer;

			if (inArray(["bottom", "top", "left", "right"], this.opts.dock)) {
				containerData.stack.push({
					tag: this,
					side: this.opts.dock,
					order: this.opts.dockOrder,
					widthHint: this.opts.dockWidth,
					heightHint: this.opts.dockHeight
				});
			} else if (this.opts.dock === "fill") {
				if (containerData.fillElement != null) {
					throw new Error("There can be only one tag with a `dock` setting of `fill` within a dockable container");
				} else {
					containerData.fillElement = this;
				}
			} else {
				throw new Error("Invalid `dock` property; must be one of bottom, top, left, right, fill");
			}
		}
	}
}