import {Directive, HostListener} from '@angular/core';
import {Map, MapMouseEvent, MapStyleDataEvent} from 'maplibre-gl';

@Directive({
  selector: 'mgl-map[auto-3d]',
  standalone: true,
})
export class MapAuto3dDirective {
  @HostListener('styleData', ['$event'])
  styleData(event: MapStyleDataEvent) {
    this.updatePitch(event.target);
  }

  @HostListener('pitchEvt', ['$event'])
  pitch(event: MapMouseEvent) {
    this.updatePitch(event.target);
  }

  updatePitch(map: Map) {
    if (map.getPitch() === 0) {
      const layer = map.getLayer('building-3d');
      if (layer && layer?.visibility !== 'none') {
        layer.visibility = 'none';
        map.setPaintProperty('building', 'fill-opacity', 1);
        map.setLayerZoomRange('building', 13, 24);
      }
    } else {
      const layer = map.getLayer('building-3d');
      if (layer && layer?.visibility !== 'visible') {
        layer.visibility = 'visible';
        map.setPaintProperty('building', 'fill-opacity', ['interpolate', ['linear'], ['zoom'], 15, 1, 16, 0]);
        map.setLayerZoomRange('building', 13, 16);
      }
    }
  }
}
