import { Component, inject, OnInit } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';
import * as AppCnst from '@app_consts';
import * as Cnst from '@app_core/consts';
import * as Utils from '@app_core/utils';
import { TranslateService } from '@ngx-translate/core';
import * as AppModule from './app.module';
import { ENVIRONMENT_TOKEN } from '@app_core/injection-tokens';
import { Globals } from '@app_core/services/globals';
import { RepositoryService } from '@app_core/services/http/repository.service';
import { ServerInfoService } from '@app_core/services/serverinfo.service';
import { LocaleService } from '@app_core/services/localization/locale.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})


export class AppComponent implements OnInit {
  private environment = inject(ENVIRONMENT_TOKEN);

  constructor(
    public globals: Globals,
    public repository: RepositoryService,
    public translate: TranslateService,
    private serverInfoService: ServerInfoService,
    private localeService: LocaleService,
    private updateService: SwUpdate

  ) {
    this.initLangCulture();
    globals.appTitle = AppCnst.APP_TITLE;
    Utils.setIndexTitle(globals.appTitle);
    globals.appTitleWithVersion = `${AppCnst.APP_TITLE} V.${this.environment.appVersion} (${this.environment.appBuild})`;
    globals.appPages = AppCnst.APP_PAGES;
    globals.mainPage = AppCnst.APP_PAGES[0];
    this.serverInfoService.defaultServerInfoVisible = false;
  }


  private initLangCulture() {
    this.translate.addLangs(AppCnst.SUPPORTED_LANGUAGES);

    const languageFromBrowser: string = navigator.language.split('-')[0];
    const startLanguage: string = Utils.isLanguageSupported(languageFromBrowser, AppCnst.SUPPORTED_LANGUAGES, Cnst.SUPPORTED_LANGUAGES) ? languageFromBrowser : AppCnst.cnst_DefaultLanguage;
    const startCulture: string = Utils.isCultureSupported(navigator.language, AppModule.SUPPORTED_CULTURES, Cnst.SUPPORTED_CULTURES) ? navigator.language : AppCnst.cnst_DefaultCulture;

    this.localeService.initLocaleLanguage(startCulture, startLanguage);
  }


  ngOnInit(): void {
    this.updateService.checkForUpdate().then((res) => { if (res) { this.updateService.activateUpdate(); window.location.reload(); } });
  }

}
