class ApiController {
    token: string;
    apiurl: string;
    

    async getApiurl() {
        let response = await fetch(`${window.location.href}apiurl`)
        if(await response.ok) {
            this.apiurl = await response.text();
            console.log(this.apiurl);
        } else { 
            console.log("Failed to get apiurl");
        }
    }


    async login(username: string , password: string) {
        let promise = await fetch(`http://localhost:8000/token/`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "accept": "application/json", 
                "access-control-allow-origin": "*",
                "Access-Control-Allow-Methods": "POST", 
                "Access-Control-Allow-Credentials": "true",                     
            },
            body: new URLSearchParams({
                username: username, 
                password: password
            })

        });
        if(await promise.ok) {
            this.token = (await promise.json())['access_token'];
           console.log(this.token);
        } else {
            console.log("Failed to login");
        }
    }

    async get(path) {
        console.log(this.token);
        let promise = await fetch(`${this.apiurl}${path}/`, {
            method: "GET", 
            headers: {
                "accept": "application/json",       
                "Authorization": `Bearer ${this.token}`,
                "Access-Control-Allow-Origin": "http://localhost:8000",
                "Access-Control-Allow-Methods": "GET", 
                "Access-Control-Allow-Credentials": "true",
            }
        });
        if(await promise.ok) {
            let data = await promise.json();
            return data;
        }
    }

    async post(path){
        let promise = await fetch(`${this.apiurl}${path}/`, {
            method: "POST", 
            headers: {
                "accept": "application/json",       
                "Authorization": `Bearer ${this.token}`,
                "Access-Control-Allow-Origin": "http://localhost:8000",
                "Access-Control-Allow-Methods": "POST", 
                "Access-Control-Allow-Credentials": "true",
            }
        });
        if(await promise.ok) {
            let data = await promise.json();
            return data;
        }

    }

    
}

export const Api = new ApiController();