import { Component, OnInit, Input, Host, OnChanges, SimpleChanges,ChangeDetectorRef } from '@angular/core';
import { MapComponent } from '@farmmaps/ng-openlayers';
import {IMapState} from '../../../models/map.state'
import {View} from 'ol';
import { fromLonLat } from 'ol/proj';


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

  view: View;
  map: MapComponent;
  @Input() position: GeolocationPosition;
  @Input() mapState: IMapState;
  @Input() animate: boolean;

  constructor(@Host() map: MapComponent,private changeDetectorRef$: ChangeDetectorRef ) {
    this.map = map;
  }

  ngOnInit() {  
    this.view = this.map.instance.getView();
    this.view.on('change:center', () => {
      this.changeDetectorRef$.detectChanges();
    });
  }

  ngOnChanges(changes: SimpleChanges) {
    // if (changes.position && this.instance) {
    //   var p = changes.position.currentValue as Position;
    //   this.instance.setPosition(fromLonLat([p.coords.longitude, p.coords.latitude]));
    //   this.locationTolerance = p.coords.accuracy;
    //   this.recalcLocationTolerance();
    //   this.heading = p.coords.heading;
    // }
  }

  p

  public centered():boolean {
    if(this.position && this.mapState) {
      const center = this.view.getCenter();
      const newCenter = fromLonLat([this.position.coords.longitude,this.position.coords.latitude]);
      const x1 = newCenter[0].toFixed(0);
      const x2 = center[0].toFixed(0);
      const y1 = newCenter[1].toFixed(0);
      const y2 = center[1].toFixed(0);
      return x1==x2 && y1==y2;  
    }
    return false;
  }

  public disabled():boolean {
    return !this.position;
  }

  handleClick(event:Event) {
    if(this.position) {
      const view = this.map.instance.getView();
      const newCenter = fromLonLat([this.position.coords.longitude,this.position.coords.latitude]);
      const extent = [newCenter[0]-500,newCenter[1]-500,newCenter[0]+500,newCenter[1]+500];
      const options = { padding: [0, 0, 0, 0],minResolution:1 };
      const size = this.map.instance.getSize();
      const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
      const threshold = 44 * rem;
      let left = 1 * rem;
      const right = 1 * rem;
      let bottom = Math.round(size[1] / 2);
      const top = 1 * rem;
      if (size[0] > threshold) {
        bottom = 1 * rem;
        left = 23 * rem;
      }
      //options.padding = [top, right, bottom, left];
      if (this.animate) options["duration"] = 2000;
      view.fit(extent, options);  
    }
    event.preventDefault();
  }
}
