import { firstValueFrom } from 'rxjs';
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Api } from '../providers/api/api';
import { AppConfig, ApplicationConfiguration, ComputerConfig } from './components/models/app.config.model';
import { DeviceDetectorService } from 'ngx-device-detector';


@Injectable({ providedIn: 'root' })
export class ConfigurationService
{
  private config: ApplicationConfiguration | undefined;
  private readonly deviceService = inject(DeviceDetectorService);

  public async loadConfig(): Promise<void>
  {
    if (!this.config)
    {
      try
      {
        //Initialize settings
        this.config = { computerConfig: new ComputerConfig(), appConfig: new AppConfig() };

        //Inject HttpClient
        const http = inject(HttpClient)

        //Load application Settings
        const appSettings = await firstValueFrom(http.get<AppConfig>('appsettings.json'));
        Api.microServiceEnabled = appSettings.microServiceEnabled;
        Api.secretKey = appSettings.secretKey;
        localStorage.setItem('OnlineSalesAutoCrop.storage1', Api.secretKey);

        Api.cipherSecretKey = appSettings.cipherSecretKey;
        localStorage.setItem('OnlineSalesAutoCrop.storage2', Api.cipherSecretKey);
        this.config.appConfig = appSettings;

        //Load Computer  Settings
        if (!(this.deviceService.isMobile() || this.deviceService.isTablet()))
        {
          let options: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json;charset=utf-8' });
          options = options.append('Accept', 'application/json');
          const body: any = { noParameter: "1" };
          this.config.computerConfig = await firstValueFrom(http.post<ComputerConfig>('http://127.0.0.1:7777/globalApi/readsettings', body, { headers: options }));
        }
      }
      catch
      {
        //Noting to do
      }
    }
  }

  public get configuration(): ApplicationConfiguration | undefined
  {
    return this.config;
  }
}
