composedPath = (el) ->
	path = []
	while (el)
		path.push(el)
		if el.tagName is 'HTML'
			path.push(document)
			path.push(window)
			return path
		el = el.parentElement

createPopup = (options) ->
	new Promise (resolve, reject) ->
		resolve(new Popup(options))

class Popup
	constructor: ({anchor, topOffset, leftOffset}) ->
		@window = window
		@visible = false
		@anchor = anchor[0]
		@topOffset = topOffset || 0
		@leftOffset = leftOffset || 0

		@el = document.createElement('div')
		@el.style = 'position:absolute;top: 0; left: 0; display: none;'
		document.body.appendChild(@el)

	append: (el) -> @el.appendChild(el[0])

	hide: ->
		@visible = false
		@el.style.display = "none"
		document.removeEventListener 'click', @hideOnClickOutside

	show: ->
		@visible = true
		@el.style.display = "block"
		@position()
		setTimeout => document.addEventListener 'click', @hideOnClickOutside

	resize: ->

	position: ->
		{top, left} = @anchor.getBoundingClientRect()
		{width, height} = @el.getBoundingClientRect()
		wWidth = window.innerWidth
		wHeight = window.innerHeight

		left += @leftOffset
		top += @topOffset

		left = Math.max(0, Math.min(wWidth - width, left - width));
		top = Math.max(0, Math.min(wHeight - height, top));

		@el.style.left = left + 'px'
		@el.style.top = top + 'px'

	hideOnClickOutside: (event) =>
		return unless @visible
		path = event.path || (event.composedPath && event.composedPath()) || composedPath(event.target)
		return if path.includes(@el)
		@hide()

	release: ->
		@el.parentNode.removeChild(@el);
		document.removeEventListener 'click', @hideOnClickOutside

module.exports = {createPopup, Popup}
