import { Client } from "./client.js";

class Account
{
	/**
	 * @param  {Client} client
	 */
	constructor (client)
	{
		/**
		 * @type  {Client} client
		 */
		this.client = client;
	}

	/**
	 * @param {String} username 
	 * @param {String} password 
	 * @returns {?Promise<Object>}
	 */
	async create(username, password)
	{
		let response = await this.client._post("/api/accounts/register", {username: username, password: password});
		let response_data = await response.json()

		if (response_data == "user created")
		{
			await this.client._update_logged(true);
			return null;
		}
		return response_data
	}

	/**
	 * @param {String} password 
	 * @returns {?Promise<Object>}
	 */
	async delete(password)
	{
		let response = await this.client._delete("/api/accounts/delete", {password: password});
		let response_data = await response.json();

		if (response.status === 403)
		{
			this.client._update_logged(false);
			return null;
		}
		if (response_data == "user deleted")
			this.client._update_logged(false);
		return response_data;
	}

	/**
	 * Get account data (username)
	 * @returns {?Promise<Object>}
	 */
	async get()
	{
		let response = await this.client._get("/api/accounts/edit");
		let response_data = await response.json();

		if (response.status === 403)
		{
			this.client._update_logged(false);
			return null;
		}
		return response_data;
	}

	/**
	 * 
	 * @param {*} data 
	 * @param {Number} password 
	 * @returns {?Object}
	 */
	async update(data, password)
	{
		data.current_password = password;
		let response = await this.client._patch_json("/api/accounts/edit", data);
		let response_data = await response.json();

		if (response.status === 403)
		{
			this.client._update_logged(false);
			return null;
		}

		return response_data;
	}
}

export { Account }
