/**
 * Wrapper
 */
class Wrapper {

	constructor(adapter) {
		this.adapter = adapter;
	}

	async initialize() {
		return await this.adapter.initialize();
	}

	async list() {
		return await this.adapter.all();
	}

	async has(id) {
		const value = await this.adapter.find(id);
		if (value) {
			return true;
		}
		return false;
	}

	async get(id, def) {

		const config = await this.adapter.find(id);

		if (!config) {
			await this.set(id, def, id.startsWith("_."));
			return {
				id,
				value: JSON.stringify(def),
				enabled: id.startsWith("_."),
				created_at: Date.now(),
				updated_at: Date.now(),
			};
		} else {
			return config;
		}

	}

	async set(id, value, enabled = null) {

		if (typeof value === "object" && value !== null) {
			throw new Error("Config values can't be arrays or objects");
		}

		if (id.startsWith("_.")) {
			enabled = true;
		}

		const obj = {
			value: JSON.stringify(value),
		};

		if (enabled !== null) {
			obj.enabled = enabled;
		}

		const config = await this.adapter.find(id);
		if (!config) {
			await this.adapter.create(id, obj);
		} else {
			await this.adapter.update(id, obj);
		}

	}

	async del(id) {

		const exists = await this.has(id);

		/* istanbul ignore else */
		if (exists) {
			await this.adapter.destroy(id);
		}

	}

	async enable(id) {
		return await this.enabled(id, true);
	}

	async disable(id) {
		return await this.enabled(id, false);
	}

	async enabled(id, enabled) {

		if (id.startsWith("_.") && !enabled) {
			throw new Error("Can't disable default values.");
		}

		const config = await this.adapter.find(id);

		if (config) {
			await this.adapter.update(id, { enabled });
		} else {
			throw new Error(`Config "${id}" doesn't exists`);
		}

	}

}

module.exports = Wrapper;
