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

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

        if (this.method === "GET" || this.method === "HEAD") {
            return settings
        }

        if (this.body === null) {
            return settings;
        }

        settings.body = this.body;
        return settings;
    }

    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" || this.method === "HEAD") {
            return {};
        }

        if (typeof(this.data) === "string") {
            return {
                "Content-Type": "text/plain"
            };
        }

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

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

        if (typeof(this.data) === "string") {
            return this.data;
        }

        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-request-__url__").format({
                url: 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.");
    }
}
