import { Component, OnInit, Input, Host, OnChanges, SimpleChanges,ChangeDetectorRef } from '@angular/core';
import { MapComponent } from 'ngx-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']
})
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) {
      let center = this.view.getCenter();
      let newCenter = fromLonLat([this.position.coords.longitude,this.position.coords.latitude]);
      let x1 = newCenter[0].toFixed(0);
      let x2 = center[0].toFixed(0);
      let y1 = newCenter[1].toFixed(0);
      let y2 = center[1].toFixed(0);
      return x1==x2 && y1==y2;  
    }
    return false;
  }

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

  handleClick(event:Event) {
    if(this.position) {
      let view = this.map.instance.getView();
      let newCenter = fromLonLat([this.position.coords.longitude,this.position.coords.latitude]);
      let extent = [newCenter[0]-500,newCenter[1]-500,newCenter[0]+500,newCenter[1]+500];
      var options = { padding: [0, 0, 0, 0],minResolution:1 };
      let size = this.map.instance.getSize();
      let rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
      let threshold = 44 * rem;
      var left = 1 * rem;
      var right = 1 * rem;
      var bottom = Math.round(size[1] / 2);
      var 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();
  }
}
