import { Component, OnInit, Input, ViewChild, ElementRef, OnChanges, SimpleChanges ,Host} from '@angular/core';
import { MapComponent } from '@farmmaps/ng-openlayers';
import  Overlay  from 'ol/Overlay';
import { fromLonLat, toLonLat } from 'ol/proj';


@Component({
  selector: 'fm-map-gps-location',
  templateUrl: './gps-location.component.html',
  styleUrls: ['./gps-location.component.scss']
})
export class GpsLocation  implements OnInit,OnChanges{

  @Input() enable:boolean;
  public instance: Overlay;
  @Input() position: GeolocationPosition;
  @Input() location: number[]=[0,0];
  @Input() locationTolerance = 0;
  @Input() showHeading = false;
  @Input() showTolerance = false;
  @Input() heading = 0;
  @Input() headingTolerance = 0;
  public locTolerancePixels = 0;
  public path = "";
  public rotate = "";
  private resolution = 0;
  initialized = false;
  @ViewChild('location', { static: true }) locationElement: ElementRef;

  constructor(private map: MapComponent) {
    
  }

  recalcLocationTolerance() {
    this.locTolerancePixels = this.resolution >0? this.locationTolerance / this.resolution:0;
  }

  ngOnInit() {
    this.instance = new Overlay({
      stopEvent:false,
      positioning: 'center-center',
      position: fromLonLat( this.location),
      element: this.locationElement.nativeElement
    });
    const x = Math.tan(this.headingTolerance * Math.PI / 180)*40;
    const y = Math.cos(this.headingTolerance * Math.PI / 180) * 40;
    const y1 = Math.round(500 - y);
    const x1 = Math.round(500 - x);
    const y2 = Math.round(y1);
    const x2 = Math.round(500 + x);
    this.path = "M " + x2 + " " + y2 + " A 45 45,0,0,0, " + x1 + " " + y1 + " L 493 500 L 507 500 Z";
    this.rotate = "rotate(" + Math.round(this.heading) + " 500 500)";
    this.locTolerancePixels = this.locationTolerance;
    this.map.instance.addOverlay(this.instance);
    this.map.instance.getView().on('change:resolution', (evt:any) => {
      this.resolution = evt.target.get('resolution');
      this.recalcLocationTolerance();
    });
    this.initialized = true;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.position && this.instance) {
      const p = changes.position.currentValue as GeolocationPosition;
      if(p && this.initialized) {
        this.instance.setPosition(fromLonLat([p.coords.longitude, p.coords.latitude]));
        this.locationTolerance = p.coords.accuracy;
        this.recalcLocationTolerance();  
      }
    }
    if(changes.heading && this.instance) {
      this.rotate = "rotate(" +   Math.round(changes.heading.currentValue) + " 500 500)";
    }
  }
}
