import { Component, Host, Input, OnInit, OnChanges, SimpleChanges, forwardRef } from '@angular/core';
import { ActivatedRoute  } from '@angular/router';
import { ViewComponent, MapComponent } from '@farmmaps/ng-openlayers';

 
@Component({
  selector: 'fm-map-zoom-to-extent',
  template: `<ng-content></ng-content>`
})
export class ZoomToExtentComponent implements OnChanges {
  view: ViewComponent;
  map: MapComponent;
  paddingTop = 0;
  paddingLeft = 0;
  paddingBottom = 0;
  paddingRight = 0;

  @Input() extent: number[];
  @Input() animate = false;

  constructor(@Host() view: ViewComponent, @Host() map: MapComponent,route: ActivatedRoute ) {
    this.view = view;
    this.map = map;
    if(route && route.snapshot && route.snapshot.data && route.snapshot.data["fm-map-zoom-to-extent"]) {
      const params = route.snapshot.data["fm-map-zoom-to-extent"];
      this.paddingTop = params["padding-top"] ? params["padding-top"] : 0;
      this.paddingBottom = params["padding-bottom"] ? params["padding-bottom"] : 0;
      this.paddingLeft = params["padding-left"] ? params["padding-left"] : 0;
      this.paddingRight = params["padding-right"] ? params["padding-right"] : 0;
    }
  }

  ngOnChanges(changes: SimpleChanges) {
    if (this.extent) {
      const options = { padding: [0, 0, 0, 0],minResolution:1 };
      const size = this.map.instance.getSize();
      const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
      const threshold = 40 * rem;
      let left = 1 * rem;
      const right = 1 * rem;
      let bottom = Math.round((size[1] / 2) + (4*rem));
      const top = 1 * rem;
      if (size[0] > threshold) {
        bottom = 5 * rem;
        left = 23 * rem;
      }
      options.padding = [top + (this.paddingTop*rem), right+ (this.paddingRight*rem), bottom + (this.paddingBottom*rem), left+ (this.paddingLeft*rem)];
      if (this.animate) options["duration"] = 1000;
      this.view.instance.fit(this.extent, options);
    }
  }
}
