/**
 * Copyright © Volker Schukai and all contributing authors, {{copyRightYear}}. All rights reserved.
 * Node module: @schukai/monster
 *
 * This source code is licensed under the GNU Affero General Public License version 3 (AGPLv3).
 * The full text of the license can be found at: https://www.gnu.org/licenses/agpl-3.0.en.html
 *
 * For those who do not wish to adhere to the AGPLv3, a commercial license is available.
 * Acquiring a commercial license allows you to use this software without complying with the AGPLv3 terms.
 * For more information about purchasing a commercial license, please contact Volker Schukai.
 *
 * SPDX-License-Identifier: AGPL-3.0
 */

import { internalSymbol, instanceSymbol } from "../../constants.mjs";
import { validateString } from "../../types/validate.mjs";
import { Datasource } from "../datasource.mjs";

export { Storage, storageObjectSymbol };

/**
 * @private
 * @type {symbol}
 */
const storageObjectSymbol = Symbol.for(
	"@schukai/monster/data/datasource/storage/@@storageObject",
);

/**
 * The class represents a record.
 *
 * @fragments /fragments/libraries/data/datasource/storage/
 *
 * @example /examples/libraries/data/datasource/storage/simple/ Read and write JSON through Web Storage
 * @example /examples/libraries/data/datasource/storage/session-draft/ Persist draft state in session storage
 * @example /examples/libraries/data/datasource/storage/local-preferences/ Persist user preferences in local storage
 * @example /examples/libraries/data/datasource/storage/remove-on-undefined/ Remove the storage entry when the datasource becomes undefined
 * @license AGPLv3
 * @since 1.22.0
 * @copyright Volker Schukai
 * @summary The Storage class encapsulates the access to data objects over WebStorageAPI.
 */
class Storage extends Datasource {
	/**
	 *
	 * @param {string} key LocalStorage Key
	 * @throws {TypeError} value is not a string
	 */
	constructor(key) {
		super();
		this.setOption("key", validateString(key));
	}

	/**
	 * This method is called by the `instanceof` operator.
	 * @return {symbol}
	 * @since 2.1.0
	 */
	static get [instanceSymbol]() {
		return Symbol.for("@schukai/monster/data/datasource/storage");
	}

	/**
	 * @property {string} key=undefined LocalStorage Key
	 */
	get defaults() {
		return Object.assign({}, super.defaults, {
			key: undefined,
		});
	}

	/**
	 * @throws {Error} this method must be implemented by derived classes.
	 * @return {external:Storage}
	 * @private
	 */
	[storageObjectSymbol]() {
		throw new Error("this method must be implemented by derived classes");
	}

	/**
	 * @return {Promise}
	 * @throws {Error} the options does not contain a valid json definition
	 * @throws {TypeError} value is not a object
	 * @throws {Error} the data cannot be read
	 */
	read() {
		const self = this;

		const storage = self[storageObjectSymbol]();

		return new Promise(function (resolve) {
			const data = JSON.parse(storage.getItem(self.getOption("key")));
			self.set(data ?? {});
			resolve();
		});
	}

	/**
	 * @return {Storage}
	 * @throws {Error} the data cannot be written
	 */
	write() {
		const self = this;

		const storage = self[storageObjectSymbol]();

		return new Promise(function (resolve) {
			const data = self.get();
			if (data === undefined) {
				storage.removeItem(self.getOption("key"));
			} else {
				storage.setItem(self.getOption("key"), JSON.stringify(data));
			}

			resolve();
		});
	}

	/**
	 * @return {Storage}
	 */
	getClone() {
		return new Storage(this[internalSymbol].getRealSubject()["options"].key);
	}
}
