if (!P5MENU_URL) throw "Missing P5MENU_URL"
if (!VERSION) throw "Missing P5Menu VERSION"

function p5UI__MenuStore() {

	var _subscribers = []

	function _subscribe( fn ) { // fn( { bookmarks, idsBookmarks, objects, urls } )
		_subscribers.push( fn )
	}

	function _update( data ) { // data: { bookmarks, idsBookmarks, objects, urls }

		data.objects.sort(function (a, b) {
			if (a.label.toLowerCase() > b.label.toLowerCase()) return 1
			if (a.label.toLowerCase() < b.label.toLowerCase()) return -1
			return 0
		})
		data.urls.sort(function (a, b) {
			if (a.label.toLowerCase() > b.label.toLowerCase()) return 1
			if (a.label.toLowerCase() < b.label.toLowerCase()) return -1
			return 0
		})

		_set('version', data.version)
		_set('bookmarks', data.bookmarks)
		_set('idsBookmarks', data.idsBookmarks)
		_set('objects', data.objects)
		_set('urls', data.urls)

		var data = _getData()
		_subscribers.forEach(function (fn) {
			fn(data)
		})
	}

	function _forceUpdate() {
		var data = _getData()
		_subscribers.forEach(function (fn) {
			fn(data)
		})
	}

	function _getData() {
		return {
			version: _get('version'),
			bookmarks: _get('bookmarks'),
			idsBookmarks: _get('idsBookmarks'),
			objects: _get('objects'),
			urls: _get('urls')
		}
	}

	function _hasData() {
		var data = _getData()
		return (
			parseInt(data.version || 0) === parseInt(VERSION)
			&& (
				null !== data.bookmarks
				|| null !== data.idsBookmarks
				|| null !== data.objects
				|| null !== data.urls
			)
		)
	}

	function _set(type, value) {
		global.localStorage.setItem('p5Menu.' + type, JSON.stringify(value))
	}

	function _get(type, value) {
		var val = global.localStorage.getItem('p5Menu.' + type)
		return val ? JSON.parse(val) : null
	}

	function _remoteUpdate(postData) {
		var options =
		window.fetch(P5MENU_URL
			, (!postData)
				?	{ method: 'GET',
						headers: { 'Content-Type': 'application/json' },
						credentials: 'same-origin',
					}
				:	{ method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						credentials: 'same-origin',
						body: JSON.stringify(postData)
					}
		).then(function (response) {
			return response.json()
		}).then(function (response) {
			if ('success' === response.type) {
				_update(response.body)
			} else {
				// err...
			}
		})
	}

	function _clearCache() {
		global.localStorage.removeItem('p5Menu.' + 'urls')
		global.localStorage.removeItem('p5Menu.' + 'objects')
		global.localStorage.removeItem('p5Menu.' + 'bookmarks')
		global.localStorage.removeItem('p5Menu.' + 'idsBookmarks')
		global.localStorage.removeItem('p5Menu.' + 'version')
	}

	return {
		subscribe: _subscribe,
		update: _update,
		forceUpdate: _forceUpdate,
		remoteUpdate: _remoteUpdate,
		getData: _getData,
		hasData: _hasData,
		clearCache: _clearCache,
	}
}
global.p5UI__MenuStore = p5UI__MenuStore()
