import { Injectable } from '@angular/core'
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'
import { Observable, forkJoin } from 'rxjs'
import { map } from 'rxjs/operators'

import { WebsocketService } from '../_services/websocket.service'

import { MapService, MaplibreStyle } from '../openapi'


export class MapboxDataAndStyle {
  constructor(
    public data: object,
    public style: MaplibreStyle,
  ) { }
}


@Injectable()
export class GeoJsonService {
  constructor(
    private _http: HttpClient,
    // private apollo: Apollo,
    public mapService: MapService,
  ) { }

  getLayer(url: string, params?: object): Observable<object> {
    if (!params) {
      params = {}
    }
    return this._http.get<object>(url, {
      headers: <HttpHeaders>params,
    })
  }

  getStyle(store: string): Observable<MaplibreStyle> {
    return this.mapService.getLayerStyleApiMapLayerStyleStoreGet({ store: store })
  }

  getAll(url: string, store: string, params?: object): Observable<MapboxDataAndStyle> {
    return forkJoin([
      this.getLayer(url, params),
      this.getStyle(store),
    ]).pipe(map(
      res => new MapboxDataAndStyle(res[0], res[1])
    ))
  }
}


@Injectable()
export class LiveGeoJsonService {
  messages = {}
  ws: any
  constructor(
    private wsService: WebsocketService
  ) { }

  connect(channel: string) {
    const hostname = window.location.hostname
    const port = window.location.port
    let protocol = window.location.protocol == 'https:' ? 'wss:' : 'ws:'
    this.wsService.connect(
      protocol + '//' + hostname + ':' + port + '/gj/live/' + channel
    )
    return this.wsService.ws
  }

  disconnect() {
    this.wsService.disconnect()
  }
}
