import Bluebird from 'bluebird'
import {parseHtml} from '../parse-html'
import forOwn from 'lodash/forOwn'
import forEach from 'lodash/forEach'
import {v4 as uuid} from 'uuid'

export class ExtensionNotLoadedError extends Error {}
export class ExtensionTooOldError extends Error {}

export function fetchHtml(url, fetchArgs) {
	if (!global.gobbldygook_extension) {
		return Bluebird.reject(new ExtensionNotLoadedError('Extension not loaded'))
	}
	if (global.gobbldygook_extension < '1.0.0') {
		return Bluebird.reject(new ExtensionTooOldError(`Extension version ${global.gobbldygook_extension_version} is too old.`))
	}

	// now we know the extension is loaded
	return new Bluebird((resolve, reject) => {
		const id = uuid()

		global.addEventListener('message', event => {
			// `event` should have the shape {from, id, text}
			if (event.data.from !== 'web-ext') {
				return
			}
			if (event.data.id !== id) {
				return
			}

			if (event.data.error) {
				reject(event.data.error)
			}
			else {
				resolve(html(event.data.text))
			}
		})

		global.postMessage({
			from: 'page',
			id,
			url,
			fetchArgs,
		}, '*')
	})
}


export function html(text) {
	return parseHtml(text)
}

export function buildFormData(obj) {
	let formData = new FormData()
	forOwn(obj, (val, key) => {
		formData.append(key, val)
	})
	return formData
}

export function getText(elems) {
	return getTextItems(elems).join('')
}

export function getTextItems(elems) {
	if (elems.children) {
		elems = elems.children
	}
	if (!elems) {
		return []
	}

	let ret = []

	forEach(elems, elem => {
		if (elem.type === 'text') {
			ret = ret.concat(elem.data.trim())
		}
		else if (elem.children && elem.type !== 'comment') {
			ret = ret.concat(getText(elem.children))
		}
	})

	return ret.filter(s => s.length)
}

export function removeInternalWhitespace(text) {
	return text.split(/\s+/).join(' ')
}

@@ -725,51 +725,38 @@
 %0A%0A%09%09
-global.addEventListener('message', 
+function handleResponse(
 event
- =%3E
+)
  %7B%0A%09
@@ -911,16 +911,74 @@
 n%0A%09%09%09%7D%0A%0A
+%09%09%09global.removeEventListener('message', handleResponse)%0A%0A
 %09%09%09if (e
@@ -1080,19 +1080,72 @@
 ))%0A%09%09%09%7D%0A
-
 %09%09%7D
+%0A%0A%09%09global.addEventListener('message', handleResponse
 )%0A%0A%09%09glo

remove the event listener when it's resolved