import { MatSnackBar } from '@angular/material/snack-bar';
import { MapSettings } from './model/MapSettings.model';
import { MapData } from './model/MapData.model';
import { MapFeatureState } from './store/map.reducers';
import { Store } from '@ngrx/store';
import { MapAttack } from './model/MapAttack.model';
import { LoadingService } from 'src/app/core/loading.service';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, enableProdMode } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { SetMapAttacksAction, SetMapTokenAction, SetMapDataAction, SetMapSettingsAction } from './store/map.actions';
import { TokenResponse } from './model/TokenResponse.model';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class MapService {

  private pendingTokenRequest: boolean = false;

  constructor(private http: HttpClient, private loadingService: LoadingService, private store: Store<MapFeatureState>, private snackBar: MatSnackBar, private router: Router) { }

  public requestMapAttacks(){
    this.loadingService.enableLoading();
    this.http.get('/tadis/map').pipe(
      finalize(() => this.loadingService.disableLoading())
    ).subscribe(
      (mapData: MapData) => {
        this.store.dispatch(new SetMapDataAction(mapData));
      }
    );
  }

  public requestMapToken(){
    if (!this.pendingTokenRequest){
      this.loadingService.enableLoading();
      this.pendingTokenRequest = true;
      this.http.get('/tadis/map/token').pipe(
        finalize(() => {
          this.loadingService.disableLoading();
          this.pendingTokenRequest = false;
        })
      ).subscribe(
        (response: TokenResponse) => {
          this.store.dispatch(new SetMapTokenAction(response.token));
        },
        (error: HttpErrorResponse) => {
          if (error.status === 503 && error.error === "Mapbox API Error"){
            this.snackBar.open('Mapová služba není momentálně dostupná.', 'zavřít', { duration: 3000, panelClass: ['light-theme'] });
            this.router.navigate(["/"]);
          }
          else{
            this.router.navigate(["/"]);
          }
        }
      );
    }
  }

  public updateMapSettings(settings: MapSettings){
    this.loadingService.enableLoading();
    this.http.put('/tadis/map/settings', settings).pipe(
      finalize(() => this.loadingService.disableLoading())
    ).subscribe(
      (settings: MapSettings) => {
        this.snackBar.open('Nastavení úspěšně uloženo', 'zavřít', { duration: 2500, panelClass: ['light-theme'] });
        this.store.dispatch(new SetMapSettingsAction(settings));
      }
    );
  }
}

