import {AsyncPipe} from '@angular/common';
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {IonFabButton} from '@ionic/angular/standalone';
import {MapService} from '@maplibre/ngx-maplibre-gl';
import {MapEventType} from 'maplibre-gl';
import {map, mergeMap, fromEventPattern, merge} from 'rxjs';
import {IonIconDirective} from 'src/app/util/ion-icon/ion-icon.directive';

@Component({
  selector: 'stapps-compass-control',
  templateUrl: './compass-control.html',
  styleUrl: './compass-control.scss',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [AsyncPipe, IonIconDirective, IonFabButton],
})
export class CompassControlComponent {
  transform = this.mapService.mapCreated$.pipe(
    mergeMap(() =>
      merge(
        fromEventPattern<MapEventType['rotate']>(
          handler => this.mapService.mapInstance.on('rotate', handler),
          handler => this.mapService.mapInstance.off('rotate', handler),
        ),
        fromEventPattern<MapEventType['pitch']>(
          handler => this.mapService.mapInstance.on('pitch', handler),
          handler => this.mapService.mapInstance.off('pitch', handler),
        ),
      ),
    ),
    map(event => {
      const pitch = event.target.transform.pitch;
      const angle = event.target.transform.angle;

      return `rotateX(${pitch}deg) rotateZ(${angle}rad)`;
    }),
  );

  constructor(readonly mapService: MapService) {}
}
