var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
export class BaseApi {
    constructor() {
        this.headers = {};
        this.routes = {};
        this.baseUrl = '/api';
        this.idField = 'id';
        this.requestCredentials = 'same-origin'; // include, same-origin, *omit (default)
        this.corsMode = 'same-origin'; // no-cors, cors, *same-origin (default)
        this.cachePolicy = 'no-cache'; // *default, no-cache, reload, force-cache, only-if-cached
        this.entities = {};
        this.hasDebugger = false;
    }
    init(settings) {
        this.settings = settings;
        if (this.settings.host) {
            this.baseUrl = settings.host;
        }
        if (this.settings.routes) {
            this.initApiRoutes(this.settings.routes);
        }
        if (this.settings.headers) {
            const self = this;
            this.settings.headers.forEach((obj) => {
                for (const k in obj) {
                    self.headers[k] = obj[k];
                }
            });
        }
        if (this['httpHeaders']) {
            // AngularJs only
            Object.keys(this.headers).forEach((k) => {
                this['httpHeaders'].set(k, this.headers[k]);
            });
        }
        // if ('withCredentials' in new XMLHttpRequest) {
        //     this.cors = true;
        // }
    }
    ;
    route(url) {
        let mappedUrl;
        Object.keys(this.routes).forEach((k) => {
            if (k === url) {
                mappedUrl = this.routes[k];
            }
        });
        if (mappedUrl) {
            return mappedUrl;
        }
        else {
            return url;
        }
    }
    // CRUD
    post(path, data) {
        return __awaiter(this, void 0, void 0, function* () {
            const result = yield fetch(`${this.baseUrl}${path}`, {
                body: JSON.stringify(data),
                cache: this.cachePolicy,
                credentials: this.requestCredentials,
                headers: this.headers,
                mode: this.corsMode,
                method: 'POST',
            })
                .then((response) => {
                if (response.status >= 400) {
                    console.log(response);
                    console.error('Bad response from server');
                    return response;
                }
                return response.json();
            })
                .catch(this.errorHandler)
                .then((data) => {
                return data;
            });
            return result;
        });
    }
    get(path, params = undefined) {
        return __awaiter(this, void 0, void 0, function* () {
            if (params) {
                path += '?';
                Object.keys(params).forEach(key => path += key + '=' + params[key] + '&');
            }
            const result = yield fetch(`${this.baseUrl}${path}`, {
                cache: this.cachePolicy,
                credentials: this.requestCredentials,
                headers: this.headers,
                mode: this.corsMode,
                method: 'GET',
            }).then((response) => {
                if (response.status >= 400) {
                    console.log(response);
                    console.log('Bad response from server');
                    return response;
                }
                return response.json();
            })
                .catch(this.errorHandler)
                .then((data) => {
                return data;
            });
            return result;
        });
    }
    // todo: patch
    patch(path, id, data) {
        return __awaiter(this, void 0, void 0, function* () {
            yield fetch(`${this.baseUrl}${path}/` + id, {
                headers: this.headers,
                // method: 'PATCH',
                method: 'patch',
                body: JSON.stringify(data)
            });
        });
    }
    // fixme: causes php server error on drupal content page
    delete(path, id) {
        return __awaiter(this, void 0, void 0, function* () {
            console.log(path, id);
            // await fetch(`${this.baseUrl}${path}/` + id, {
            //     headers: this.headers,
            // //  method: 'DELETE'
            //     method: 'delete'
            // });
        });
    }
    login(username, password) {
        console.log(username, password.length);
    }
    logout(namespace = 'app:authData', refresh = false) {
        this.clearCredentials(namespace);
        this.settings.authenticated = false;
        if (refresh) {
            // location.href = location.origin;
            location.href = location.href;
        }
    }
    // todo: use btoa + atob
    setCredentials(credentials, namespace = 'app-auth') {
        this.credentials = credentials;
        // window.localStorage.setItem(namespace, btoa(JSON.stringify(credentials)));
        if (typeof window !== 'undefined') {
            window.localStorage.setItem(namespace, JSON.stringify(credentials));
        }
    }
    getCredentials(namespace = 'app:authData') {
        if (typeof window !== 'undefined' && window.localStorage.getItem(namespace)) {
            // return JSON.parse(atob(window.localStorage.getItem(namespace)));
            return JSON.parse(window.localStorage.getItem(namespace));
        }
    }
    clearCredentials(namespace = 'app:authData') {
        if (typeof window !== 'undefined' && window.localStorage.getItem(namespace)) {
            window.localStorage.removeItem(namespace);
        }
    }
    initApiRoutes(routes) {
        const self = this;
        routes.forEach((obj) => {
            for (let k in obj) {
                self.routes[k] = obj[k];
            }
        });
        if (self.settings.dev && self.settings.routes_dev) {
            self.settings.routes_dev.forEach((obj) => {
                for (let k in obj) {
                    self.routes[k] = obj[k];
                }
            });
        }
    }
    // todo
    errorHandler(error) {
        // AppService.scope.$broadcast('formError', error);
        console.error(error);
        if (!error) {
            return;
        }
        // if(error.data === "token expired"){
        //     toastr.warning($filter('translate')('LOGIN EXPIRED')+'.');
        //     service.logOut();
        //     return;
        // }
        // if (error.statusText === 'Bad Request' || error.status == 400) {
        //     if (error.data.message) {
        //         toastr.warning($filter('translate')(error.data.message));
        //     } else {
        //         toastr.warning($filter('translate')('ERROR BAD REQUEST') + '.');
        //     }
        // }
        // if(error.statusText === 'Unauthorized' || error.status == 401){
        //     toastr.warning($filter('translate')('UNAUTHORIZED ERROR')+'.');
        //     service.logOut();
        //     return;
        // }
        // if(error.statusText === 'Not found' || error.status == 404){
        //     toastr.warning($filter('translate')('ERROR NOT FOUND')+'.');
        // }
    }
    // entities local storage todo: move to storage.js
    saveLocalResource(resource) {
        localStorage.setItem(resource[this.idField], resource);
    }
    loadLocalResource(ID) {
        if (localStorage.getItem(ID)) {
            localStorage.getItem(ID);
        }
    }
    flushLocalResource(ID) {
        if (localStorage.getItem(ID)) {
            localStorage.removeItem(ID);
        }
    }
}
//# sourceMappingURL=base-api.js.map