/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import {
  ChangeDetectionStrategy,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild,
} from '@angular/core';
import type { Coordinate } from 'ol/coordinate';
import Map from 'ol/Map';
import Overlay from 'ol/Overlay';

@Component({
  selector: 'bci-open-layers-overlay',
  templateUrl: './open-layers-overlay.component.html',
  styleUrls: ['./open-layers-overlay.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OpenLayersOverlayComponent implements OnInit, OnChanges {
  @ViewChild('popup', { static: true }) popup: ElementRef;
  @Input() position: Coordinate;
  @Input() map: Map;
  @Output() closed = new EventEmitter<boolean>();
  private _overlay: Overlay;

  ngOnChanges(changes: SimpleChanges): void {
    if (this._overlay && changes['position']) {
      this._overlay.setPosition(this.position);
      this.closed.emit(false);
    }
    if (this._overlay && this.map) {
      this.map.addOverlay(this._overlay);
    }
  }

  ngOnInit() {
    const overlayOptions = {
      element: this.popup.nativeElement,
      autoPan: true,
      /*autoPanAnimation: {
        duration: 250
      }*/
    };
    this._overlay = new Overlay(overlayOptions);
  }

  closePopup() {
    this._overlay.setPosition(undefined);
    this.closed.emit(true);
  }
}
