import {ChangeDetectionStrategy, Component, Input, Optional} from '@angular/core';
import {GeoJSONSourceComponent, LayerComponent, MapService} from '@maplibre/ngx-maplibre-gl';
import {FeatureCollection, Polygon} from 'geojson';
import {SCFeatureProperties} from '../feature-collection.pipe';
import {
  FillLayerSpecification,
  LineLayerSpecification,
  MapLayerMouseEvent,
  SymbolLayerSpecification,
} from 'maplibre-gl';
import {DataRoutingService} from '../../data/data-routing.service';
import {MapDataProvider} from '../map-data.provider';
import {fromEvent, map, startWith, Observable} from 'rxjs';
import {AsyncPipe} from '@angular/common';

/**
 * Get a CCS variable value
 */
function getCssVariable(color: string) {
  return getComputedStyle(document.documentElement).getPropertyValue(color);
}

@Component({
  selector: 'stapps-building-markers',
  templateUrl: './building-markers.html',
  styleUrl: './building-markers.scss',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [GeoJSONSourceComponent, LayerComponent, AsyncPipe],
})
export class BuildingMarkersComponent {
  accentColor = getCssVariable('--ion-color-primary');

  haloColor = fromEvent<MediaQueryListEvent>(
    window.matchMedia('(prefers-color-scheme: dark)'),
    'change',
  ).pipe(
    map(() => getCssVariable('--ion-background-color')),
    startWith(getCssVariable('--ion-background-color')),
  );

  buildingPaint: LineLayerSpecification['paint'] = {
    'line-color': this.accentColor,
    'line-width': 2,
  };

  buildingFillPaint: FillLayerSpecification['paint'] = {
    'fill-color': `${this.accentColor}22`,
  };

  buildingLabelLayout: SymbolLayerSpecification['layout'] = {
    'text-field': '{name}',
    'text-font': ['barlow-700-normal'],
    'text-max-width': 8,
    'text-size': 13,
  };

  buildingLabelPaint: Observable<SymbolLayerSpecification['paint']> = this.haloColor.pipe(
    map(haloColor => ({
      'text-color': this.accentColor,
      'text-halo-color': haloColor,
      'text-halo-width': 1,
    })),
  );

  @Input({required: true}) data: FeatureCollection<Polygon, SCFeatureProperties>;

  constructor(
    @Optional() readonly dataProvider: MapDataProvider | null,
    readonly dataRoutingService: DataRoutingService,
    readonly mapService: MapService,
  ) {}

  async featureClick(event: MapLayerMouseEvent) {
    if (this.dataProvider === null) return;

    if (event.originalEvent.target !== event.target._canvas) return;
    const feature = event.features?.[0];
    if (!feature) return;

    const item = this.dataProvider.current.value?.data.find(it => it.uid === feature.properties.uid);
    if (item === undefined) return;

    this.dataRoutingService.emitChildEvent(item);
  }
}
