import { Component, OnInit, OnDestroy, Inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { loadScript, ILoadScriptOptions } from 'esri-loader';

import { AppService } from 'app/core/app.service';
import { AppConfigService } from 'app/app-config/app-config.service';
import { FunctionAttributes } from 'app/app-config/function-config';
import { AuthenticationService } from 'app/authentication/authentication.service';
import { ARCGISJSAPI_CONFIG } from 'app/core/provider-name-token';
import { ArcgisjsapiConfig } from 'app/core/arcgisjsapi-config';


@Component({
  selector: 'app-gis',
  templateUrl: './gis.component.html',
  styleUrls: ['./gis.component.scss']
})
export class GisComponent implements OnInit, OnDestroy {

  get systemName(): string | null {
    return this.appService.currentSystem?.SYSTEM_NAME || null;
  }

  public functions: FunctionAttributes[] = [];

  constructor(
    private route: ActivatedRoute,
    private appService: AppService,
    private appConfigService: AppConfigService,
    public authenticationService: AuthenticationService,
    @Inject(ARCGISJSAPI_CONFIG) private arcgisjsapiConfig: ArcgisjsapiConfig
  ) { }

  async ngOnInit() {
    const systemId = this.route.snapshot.data.systemId;
    this.appService.currentSystem = this.appConfigService.getSystemFromId(systemId);
    this.functions = this.appConfigService.getFunctionsFromSystemId(systemId);

    const loaderOptions: ILoadScriptOptions = {
      url: this.arcgisjsapiConfig.js,
      css: this.arcgisjsapiConfig.css
    };
    // Before use anything from @atlasx/gis, please call loadScript.
    await loadScript(loaderOptions);
  }

  ngOnDestroy() {
    this.functions = [];
  }

}
