import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { environment } from 'environments/environment';
import { Observable } from 'rxjs';
import { HttpResponse, HttpClient } from '@angular/common/http';
import { BaseHttpService } from '../http/base-http.service';
import { Language } from '@app/models/language/Language';
import { ConfigurationService } from '../configuration/configuration.service';

const availableLanguages: any[] = require('../../../../assets/resources/language.json');

@Injectable()
export class LanguageService {
	private currentLanguage: string;
	private languageUrl : string;

	constructor(
		private translate: TranslateService,
		private http: HttpClient,
		private baseHttp: BaseHttpService,
		private configurationService: ConfigurationService
	) {
		this.languageUrl = `${configurationService.server}language`;
		this.currentLanguage = this.configurationService.defaultLanguage || 'en';
	}

	public changeLanguage(lang: string) {
		this.currentLanguage = lang;
		this.translate.use(lang);
	}

	public getCurrentLanguage() {
		return this.currentLanguage;
	}

	public getCurrentLanguageJSON(): Observable<HttpResponse<Blob>> {
		return this.http.get(`${this.languageUrl}/${this.currentLanguage}`, { responseType: 'blob', observe: 'response' });
	}

	public updateLanguage(json: string): Observable<String> {
		return this.baseHttp.post<string>(`${this.languageUrl}/update/${this.currentLanguage}`, json);
	}

	public getCurrentLanguageName() {
		let result: string = '';
		availableLanguages.forEach(language => {
			if (language.value === this.currentLanguage) {
				result = this.translate.instant(language.label);
			}
		});
		return result;
	}

}
