import { login_manager } from "./login_manager.js";

export class request {
    get settings() {
        return {
            "method":  this.method,
            "headers": this.headers,
            "body": this.body
        };
    }

    get _apikey() {
        const manager = new login_manager();

        if (manager.logged_in) {
            return manager.apikey;
        }

        throw new Error("User must be logged in.");
    }

    get method() {
        throw new TypeError("It must be overwrite.");
    }

    get url() {
        throw new TypeError("It must be overwrite.");
    }
    
    get headers() {
        if (this.method === "GET") {
            return {};
        }

        return {
            "Content-Type": "application/json"
        };  
    }   

    get body() {
        if (this.data === null) {
            return "";
        }

        return JSON.stringify(this.data);
    }

    get _response() {
        throw new TypeError("It must be overwrite.");
    }

    async connect() {
        const request = await fetch(this.url, this.settings);

        if (!request.ok) {
            throw new Error("Fail when requested: \"" + this.url + "\".");
        }

        const response = await request.json();

        if (!("result" in response)) {
            throw new Error("Bad response, not contain result.");
        }

        return new this._response(response);
    }

    get data() {
        throw new TypeError("This must be overwrite.");
    }
}
