class API {

    constructor(base){
        this.apiBase = base;
    }

    async sendRequest(endpoint,method='GET',data=null,authenticated=false) {

        let url = this.apiBase + endpoint;
        let options = {
            method: method,
            headers: {
                "Content-Type": "application/json",
            },
        };

        if(authenticated)
        {
            options.headers['Auth'] = this.getAuthToken();
        }

        if(data)
        {
            options.body = JSON.stringify(data);
        }

        let res = await fetch(url, options);
        let json = res.json();
        if(res.status < 200 || res.status >= 300)
        {
            json.httpCode = res.status
            return json;
        }
        return json;
    }

    async GET(endpoint,authenticated) {
        return this.sendRequest(endpoint,'GET',null,authenticated);
    }

    async POST(endpoint,data,authenticated) {
        return this.sendRequest(endpoint,'POST',data,authenticated);
    }

    getAuthToken() {
        let authToken = localStorage.getItem("auth-token");
        if(!authToken) {
            return '';
        }
        return authToken;
    }

    async login(email,password) {
        let res = await this.POST('/getLoginToken.php',{
            email: email,
            password: password
        });

        if(!res.success)
        {
            return res;
        }

        let authToken = res.auth_token;
        localStorage.setItem("auth-token",authToken);
        return {
            success: true,
        }
    }

    logout() {
        localStorage.removeItem("auth-token");
    }
}
const api = new API('http://tim-uwe.de/immodata/api/');