import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { isEmpty } from 'rxjs/operators';

@Injectable({
    providedIn: 'root',
})
export class I18nService {

    locale: String;
    locales = ["de-informal"];
    i18n: any;

    constructor(private http: HttpClient) {
        let browserLocale = navigator.language;

        if (browserLocale.indexOf("-") != -1) {
            browserLocale = browserLocale.split("-")[0];
        }

        let locale = localStorage.getItem("bstly.locale") || browserLocale || this.locales[0];

        if (locale == 'de') {
            locale = 'de-informal';
        }

        if (this.locales.indexOf(locale) == -1) {
            locale = this.locales[0];
        }


        this.setLocale(locale);
    }

    getLocales() {
        return this.locales;
    }

    getLocale() {
        return this.locale;
    }

    setLocale(locale) {
        this.locale = locale;
    }

    async fetch(locale) {
        this.i18n = await this.http.get("./assets/i18n/" + locale + ".json").toPromise();
    }

    get(key, args: any[]): String {
        return this.getInternal(key, args, this.i18n);
    }

    getInternal(key, args: any[], from): String {
        if (!from) {
            return key;
        } else if (from[key]) {
            if (from[key]["."]) {
                return this.insertArguments(from[key]["."], args);
            }
            return this.insertArguments(from[key], args);
        } else {
            let keys = key.split(".");
            if (from[keys[0]]) {
                key = keys.slice(1, keys.length).join(".");
                return this.getInternal(key, args, from[keys[0]])
            }
        }

        return key;
    }

    insertArguments(label: String, args: any[]) {
        if (args) {
            for (let index in args) {
                label = label.replace(`{${index}}`, args[index]);
            }
        }
        return label;
    }

}