import {
  AfterContentInit, OnInit,
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  Input,
  OnDestroy,
  ViewChild,
} from '@angular/core';
import { IControl, ControlPosition } from 'maplibre-gl'
import { MapService } from '@maplibre/ngx-maplibre-gl'

export class CustomControl implements IControl {
  constructor(private container: HTMLElement) {}

  onAdd() {
    return this.container;
  }

  onRemove() {
    return this.container.parentNode!.removeChild(this.container);
  }

  getDefaultPosition(): ControlPosition {
    return 'top-right';
  }
}

@Component({
  selector: 'app-mgl-control',
  template:
    '<div [class]="clsName" #content><ng-content></ng-content></div>',
  styleUrls: ['app-control.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppControlComponent<T extends IControl>
  implements OnInit, OnDestroy, AfterContentInit {
  private controlAdded = false;
  clsName: string

  /* Init inputs */
  @Input() position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';

  @ViewChild('content', { static: true }) content: ElementRef;

  control: T | CustomControl;

  constructor(private MapService: MapService) {}

  ngOnInit() {
    this.clsName = "app-maplibregl-ctrl " + (this.position.endsWith('left') ? 'left' : 'right')
  }

  ngAfterContentInit() {
    if (this.content.nativeElement.childNodes.length) {
      this.control = new CustomControl(this.content.nativeElement);
      this.MapService.mapCreated$.subscribe(() => {
        this.MapService.addControl(this.control!, this.position);
        this.controlAdded = true;
      });
    }
  }

  ngOnDestroy() {
    if (this.controlAdded) {
      this.MapService.removeControl(this.control);
    }
  }
}

