<template>
	<div ref="whole">
		<div class="topbar" ref="topbar">
			<slot class="top-link"></slot>
		</div>
		<span class="arrow">
			<span class="top-link" ref="dropdownbutton">vv</span>
			<div class="dropdown" ref="dropdown" />
		</span>
	</div>
</template>

<script>
	export default {
		methods: {
			onResize() {
				this.update()
			},

			update() {
				let topbar = this.$refs.topbar
				let dropdown = this.$refs.dropdown
				
				let dropDownButton = this.$refs.dropdownbutton
				dropDownButton.classList.remove('alone', 'full')
				let dropdownWidth = dropDownButton.offsetWidth
				
				let topbarElements = Array.from(topbar.childNodes)
				let dropboxElements = Array.from(dropdown.childNodes)
				for(let el of dropboxElements) {
					dropdown.removeChild(el)
					topbar.appendChild(el)
				}

				let childAndSize = []
				for(let child of topbarElements.concat(dropboxElements)) {
					childAndSize.push([child.offsetWidth, child])
				}

				topbar.innerHTML = ''
				let width = this.$refs.whole.clientWidth - dropdownWidth - 50
				let tmp = 0
				for(let child of childAndSize) {
					tmp += child[0]

					if(width > tmp) {
						topbar.appendChild(child[1])
					} else {
						dropdown.appendChild(child[1])
					}
				}

				if(dropdown.childNodes.length === 0) {
					dropDownButton.classList.add('full')
				} else if(topbar.childNodes.length === 0) {
					dropDownButton.classList.add('alone')
				}
			}
		},

		mounted() {
			window.addEventListener('resize', this.onResize)
			//Initial menu sorting
			this.update()			
		},

		beforeDestroy() {
			//TBI never will be closed...!
			window.removeEventListener('resize', this.onResize)
		}
	}
</script>

<style scoped>
	.whole {
		box-sizing: border-box;
	}

	.topbar > .top-link:first-child {
		border: none;
	}
	.top-link {
		box-sizing: border-box;
		white-space: nowrap;
		display: inline-block;
		padding: 0.2em 0.3em 0.2em 0.3em;
		border-left: solid 1px #aaa;

		color: #aaa;
		text-decoration: none;
	}

	.alone {
		border-left: none;
	}

	.full {
		display: none;
	}

	.topbar {
		box-sizing: border-box;
		display: inline-block;
	}
	.arrow {
		position: relative;
	}

	.dropdown {
		display: none;
		position: absolute;
		
		z-index: 1;

		min-width: 100%;
		top: 1.3em;
		left: 50%;
		transform: translateX(-50%);
	}

	.dropdown .top-link {
		border: none;
		border-top: 1px solid #aaa;
		display: block;
		position: relative;
		background-color: #222;
	}

	.arrow:hover .dropdown {
		display: inline-block;
	}

	.top-link:hover {
		background-color: #333;
		color: #ddd;
	}
</style>