import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { MapDTO, DefaultMapDTO, MapFullDTO } from '../Models/map.model';
import { LocationDTO } from '../Models/location.model';

@Injectable({
  providedIn: 'root'
})
export class MapService {
  private baseUrl = 'http://localhost:8080/api/maps';
  // Local subject that holds the current active map and allows components to subscribe
  private activeMapSubject: BehaviorSubject<any | null> = new BehaviorSubject<any | null>(null);

  constructor(private http: HttpClient) {
    // populate initial active map state
    this.refreshActiveMap();
  }
  
  // Initialize active map on service creation
  

  /**
   * Fetch the current active map from backend and push it to activeMapSubject.
   * Call this after changes that may affect the active/default map.
   */
  refreshActiveMap(): void {
    this.getActiveMap().subscribe({
      next: (m) => this.activeMapSubject.next(m),
      error: (err) => {
        console.warn('Could not refresh active map', err);
        this.activeMapSubject.next(null);
      }
    });
  }

  /** Observable that components can subscribe to for active-map updates. */
  getActiveMap$(): Observable<any | null> {
    return this.activeMapSubject.asObservable();
  }

  getActiveMap(): Observable<MapDTO> {
    return this.http.get<MapDTO>(`${this.baseUrl}/active`);
  }

  getMapLocations(mapId: number): Observable<LocationDTO[]> {
    return this.http.get<LocationDTO[]>(`${this.baseUrl}/${mapId}/locations`);
  }

  // Default map methods
  getAllDefaultMaps(): Observable<DefaultMapDTO[]> {
    return this.http.get<DefaultMapDTO[]>(`${this.baseUrl}/all`);
  }

  getDefaultMap(): Observable<DefaultMapDTO> {
    return this.http.get<DefaultMapDTO>(`${this.baseUrl}/default`);
  }

  saveDefaultMap(mapDTO: DefaultMapDTO): Observable<DefaultMapDTO> {
    return this.http.post<DefaultMapDTO>(`${this.baseUrl}/default`, mapDTO);
  }

  setActiveMap(id: number): Observable<DefaultMapDTO> {
    return this.http.post<DefaultMapDTO>(`${this.baseUrl}/activate/${id}`, {});
  }

  getMapByCountry(countryName: string): Observable<DefaultMapDTO> {
    return this.http.get<DefaultMapDTO>(`${this.baseUrl}/country/${countryName}`);
  }

  deleteDefaultMap(id: number): Observable<void> {
    return this.http.delete<void>(`${this.baseUrl}/${id}`);
  }
}
