import { Account } from "./account.js"; function getCookie(name) { let cookie = {}; document.cookie.split(';').forEach(function(el) { let split = el.split('='); cookie[split[0].trim()] = split.slice(1).join("="); }) return cookie[name]; } class Client { constructor(url) { this._url = url; this.account = new Account(this); this._logged = undefined; } async isAuthentificate() { if (this._logged == undefined) this.logged = await this._test_logged(); return this.logged; } async _get(uri) { let response = await fetch(this._url + uri, { method: "GET", }); return response; } async _post(uri, data) { let response = await fetch(this._url + uri, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify(data), }); return response; } async _delete(uri, data) { let response = await fetch(this._url + uri, { method: "DELETE", headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify(data), }); return response; } async _patch_json(uri, data) { let response = await fetch(this._url + uri, { method: "PATCH", headers: { "X-CSRFToken": getCookie("csrftoken"), "Content-Type": "application/json", }, body: JSON.stringify(data), }); return response; } async login(username, password) { let response = await this._post("/api/accounts/login", {username: username, password: password}) let data = await response.json(); if (data == "user connected") { this.logged = true; return null; } return data; } async logout() { await this._get("/api/accounts/logout"); this.logged = false; } async _test_logged() { let response = await this._get("/api/accounts/logged"); let data = await response.json(); return data === "True"; } } export {Client}