﻿import {Injectable, Inject} from '@angular/core';
import { TRANSLATIONS } from './tfabrica.translations'; // import our opaque tokenimport { Http, Headers, Response, RequestOptions } from "@angular/http";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import { Subscription }   from 'rxjs/Subscription';
import { Http, Headers, Response, RequestOptions } from "@angular/http";

import { TfabricaSharedService } from '../main/tfabrica.shared.service';

@Injectable()
export class TfabricaTranslateService  {
    private _currentLang: string;
    public dictionary: any;
    public supportedLanguages: any[];
    subscription: Subscription;

    public get currentLang() {
        return this._currentLang;
    }

    // inject our translations
    constructor(
        @Inject(TRANSLATIONS) private _translations: any,
        private http: Http,
        private _shared: TfabricaSharedService
    ) {
        console.log("TfabricaTranslateService Contructor");

        let actThis = this;

        this.supportedLanguages = JSON.parse(localStorage.getItem('supportedLanguages'));

        this.InitTranslateData();

        this.subscription = _shared.changeTranslationsLanguage$.subscribe(
            newlanguage => {
                console.log("TfabricaTranslateService called from sharedService");
                console.log("new language: " + newlanguage);
                this.use(newlanguage);
            }
        );

        if (this._shared.currentLang != "") {
            this.use(this._shared.currentLang);
        }
        
    }


    public InitTranslateData() {

        let actThis = this;

        try {
            this.getSupportedLanguages().subscribe(
                result => {
                    console.log(result);
                    actThis.supportedLanguages = result;
                    actThis.setDictionaryFromApi();

                    localStorage.setItem('supportedLanguages', JSON.stringify(actThis.supportedLanguages));

                    actThis._shared.translationsIsReady(actThis.supportedLanguages);
                    if (this._shared.currentLang != "") {
                        this.use(this._shared.currentLang);
                    }
                },
                err => {
                    // Log errors if any
                    console.log(err);
                });
        } catch (Err) { }
    }


    public use(lang: string): void {
        // set current language
        this._currentLang = lang;
    }

    private translate(key: string): string {
        // private perform translation
        let translation = key;
        
        if (this._translations[this.currentLang] && this._translations[this.currentLang][key]) {
            return this._translations[this.currentLang][key];
        }

        return translation;
    }

    public instant(key: string) {
        // call translation
        return this.translate(key);
    }

    public setLangDictionary(lang: string) {

        let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
        let options = new RequestOptions({ headers: headers }); // Create a request option
        let urlTranslation = this._shared.appSettings.gettranslationsApiUrl() + lang;

        //console.log(urlTranslation);

        return this.http.get(urlTranslation, options) 
            .map((res: Response) => {
                //console.log(res);
                this._translations[lang] = res.json();
            }) // ...and calling .json() on the response to return data
            .catch((error: any) => 
                Observable.throw(error.json().error || 'Server error')
            ); //...errors if any
    }

    public setDictionaryFromApi() {
        let actThis = this;
        this.supportedLanguages.forEach(function (entry) {
            actThis.setLangDictionary(entry.value).subscribe(
                result => {
                    //console.log(result);
                },
                err => {
                    // Log errors if any
                    console.log(err);
                });

        });      
    }

    public getSupportedLanguages() {

        try {

            let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
            let options = new RequestOptions({ headers: headers }); // Create a request option
            let urlTranslation = this._shared.appSettings.supportedLanguagesApiUrl;
            urlTranslation = this._shared.appSettings.getsupportedLanguagesApiUrl();

            return this.http.get(urlTranslation, options)
                .map((res: Response) => {
                    return res.json();
                }) // ...and calling .json() on the response to return data
                .catch((error: any) =>
                    Observable.throw(error.json().error || 'Server error')
                ); //...errors if any
        } catch (Err) { }
    }

}