import {BASE} from '@/services/api.ts';
import Map from 'ol/Map'
import { Feature } from 'ol'
import { Polygon } from 'ol/geom'
import { fromLonLat } from 'ol/proj'
import { Style, Stroke } from 'ol/style'
import { Vector as VectorLayer } from 'ol/layer'
import { Vector as VectorSource } from 'ol/source'

export class RangeLayer {
	private map:    Map
	private layer!: VectorLayer<VectorSource>
	visible = false

	constructor(map: Map) { this.map = map }

	async show() {
		if (this.visible) return
		this.visible = true

		const points: [number, number][] = await fetch(`${BASE}/api/range`).then(r => r.json())
		const coords = points.map(([lat, lon]: number[]) => fromLonLat([<number>lon, <number>lat]))
		coords.push(<any>coords[0]) // close the polygon

		const feature = new Feature({ geometry: new Polygon([coords]) })
		feature.setStyle(new Style({
			stroke: new Stroke({ color: 'rgb(0 171 138 / 0.53)', width: 1.5 })
		}))

		const source = new VectorSource({ features: [feature] })
		this.layer = new VectorLayer({ source, zIndex: 50 })
		this.map.addLayer(this.layer)
	}

	hide() {
		if (!this.visible) return
		this.visible = false
		this.map.removeLayer(this.layer)
	}
}
