import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {AppConfigModel} from './app.config.model';



@Injectable()
export class AppConfig {
  static config: AppConfigModel;
  static debugConfig: AppConfigModel = {
    Server: 'https://svr2021.lawipac.com:8080/api/v1/',
    Socket: 'wss://svr2021.lawipac.com:8080/api/v1/ws'
  };

  static productionConfig: AppConfigModel = {
    Server: 'https://c5016.biukop.com.au:8080/api/v1/',
    Socket: 'wss://c5016.biukop.com.au:8080/api/v1/ws'
  };

  constructor(private http: HttpClient) {}

  load(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      const el: HTMLElement = document.getElementById('config');
      try {
        if ( location.href.includes('//localhost:4200/') ) {
          AppConfig.config = AppConfig.debugConfig;
          console.log('Using Debug Config:', AppConfig.config);
        }else{
          const json = this.decode(el.innerText);
          AppConfig.config = JSON.parse(json);
          console.log('Using Production Config:', AppConfig.config);
        }
        resolve();
      }catch (e){
        console.log('cannot load config');
        alert('Failed to load configuration, please contact administrator');
        AppConfig.config = AppConfig.productionConfig; // fallback to hardcoded config
        console.log('fall back to built-in config', AppConfig.config);
        resolve();
        // reject();
      }
    });
  }

  decode(strIn: string): string {
      return atob(strIn);
  }

  public get apiUrl(): string {
    return AppConfig.config.Server;
  }

  public get apiWsUrl(): string {
    return AppConfig.config.Socket;
  }

  public getUrl(key: string): string{
    const s = this.apiUrl + key;
    const kvPair: {key: string, value: string}[] = [
      {key: 'login',  value: this.apiUrl + 'login'},
      {key: 'logout', value: this.apiUrl + 'logout'}
    ];

    kvPair.forEach( item => {
      if  ( item.key === key) {
        return item.value;
      }
    });

    // not found if arrive here
    return s;
  }

}
