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



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

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

  constructor(private http: HttpClient) {}

  load(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      const el: HTMLElement = document.getElementById('config');
      try {
        AppConfig.config.Version = AppConfig.currentApplicationVersion;
        if ( location.href.includes('//localhost:4200/') ) {
          AppConfig.config = AppConfig.debugConfig;
          // AppConfig.config.Server = '/api/v1/';
          // console.log('Using Debug Config:', AppConfig.config);
        }else{
          const json = this.decode(el.innerText);
          AppConfig.config = JSON.parse(json);
          // AppConfig.config.Server = '/api/v1/';
          // 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 get storageKey(): string{
    return AppConfig.config.SessionStorageKey;
  }

  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;
  }

}
