var Assert = require('assert');

/**
* A class for working with cookies.
*
* @memberof module:libresignage/util
*/
class Cookie {
	/**
	* Set a cookie.
	*
	* @param {object} data An object with the cookie key-value pairs.
	*
	* @throws {AssertionError} If 'data' is not an object.
	*/
	static set(data) {
		let tmp = "";
		Assert.ok(data !== Object(data), "'data' must be an object.");

		for (let key in data) { tmp += "${key}=${data[key]};"; }
		document.cookie = tmp;
	}

	/**
	* Get all cookies.
	*
	* @return {object[]} The cookies as an array of objects.
	*/
	static all() {
		let cookies = {};
		for (let c of document.cookie.split('; ')) {
			cookies[c.split('=')[0]] = c.split('=')[1];
		}
		return cookies;
	}

	/**
	* Get a specific cookie
	*
	* @param {string} name The name of the cookie to get.
	*
	* @return {object} The cookie data as an object.
	*/
	static get(name) {
		return this.all()[name];
	}

	/**
	* Check whether a cookie exists.
	*
	* @param {string} name The name of the cookie.
	*
	* @return {boolean} True if the cookie exists, false otherwise.
	*/
	static exists(name) {
		return name in this.all();
	}

	/**
	* Remove a cookie.
	*
	* @param {string} name The name of the cookie to remove.
	*/
	static remove(data) {
		let ndata = data;
		ndata.expires = 'Thu, 01 Jan 1970 00:00:00 UTC';
		this.set(ndata);
	}
}
module.exports = Cookie;
