import { Injectable } from '@angular/core';
import { LanguageData } from './language.model';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { ConfigData } from './configdata';

var Buffer = require('buffer/').Buffer;

@Injectable({
  providedIn: 'root'
})

export class LanguageService {
//
// URL for test using REST API to local MariaDB database 
//  private baseURL = 'http://localhost:8080/zgointl';
//  
// URL for test using REST API to local MongoDB database 
//  private baseURL = 'http://localhost:5000/zgointl';
//
// URL for access MongoDB database from remote server 
  private baseURL = ConfigData.Be_URL + 'api/getlang';
  private loginURL = ConfigData.Be_URL + 'getloginlang';
  private mainURL = ConfigData.Be_URL + 'getmainlang';
  private scanURL = ConfigData.Be_URL + 'getscanlang';

  public zgoLanguage: string = '';

  private session: string|null = '';

  constructor(private http:HttpClient) { 
	  this.session = localStorage.getItem('s4z_token');
  }

  getViewElements ( viewName:string )  {
    //
    // Get default language from localStorage
    //
    const def_zgoLanguage = localStorage.getItem('zgo_language');
    // 
    // Set authorizacion paramaters 
    //
    const Auth = 'Basic ' + Buffer.from(ConfigData.UsrPwd).toString('base64');
    const reqHeaders = new HttpHeaders().set('Authorization', Auth);

    if ( def_zgoLanguage == null ) {
      this.zgoLanguage = 'en-US';
      localStorage.setItem('zgo_language',this.zgoLanguage);
    } else {
      this.zgoLanguage = def_zgoLanguage;
    }
    //
    // Get component's text data from language database
    //
	const params = new HttpParams().append('session', this.session!);
	if (viewName === 'login') {
		return this.http.get<LanguageData>(this.loginURL + '/?lang=' + this.zgoLanguage, {headers: reqHeaders, params: params});
	} else if (viewName === 'main') {
		return this.http.get<LanguageData>(this.mainURL + '/?lang=' + this.zgoLanguage, {headers: reqHeaders, params: params});
	} else if (viewName === 'scan') {
		return this.http.get<LanguageData>(this.scanURL + '/?lang=' + this.zgoLanguage, {headers: reqHeaders, params: params});
	} else {
		return this.http.get<LanguageData>(this.baseURL + 
										   '/?lang=' + this.zgoLanguage +
										   '&component=' + viewName
						,{ headers : reqHeaders
						  , params: params
						}
										  );
	}
  }  
}
