import { Component, OnInit, Input, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { IItemLayer } from '../../../models/item.layer';
import { Store } from '@ngrx/store';
import * as mapReducers from '../../../reducers/map.reducer';
import * as mapActions from '../../../actions/map.actions';
import { MapComponent } from '@farmmaps/ng-openlayers';
import { ILayervalue } from '../../../models/layer.value';
import { Observable, interval, Subject } from 'rxjs';
import { debounce, throttle } from 'rxjs/operators';
import { toLonLat } from 'ol/proj';
import { toStringHDMS } from 'ol/coordinate';
import { ClipboardService } from 'ngx-clipboard'
import { GeoJSON, WKT } from 'ol/format';
import { Point } from 'ol/geom';

@Component({
  selector: 'fm-map-layer-values',
  templateUrl: './layer-values.component.html',
  styleUrls: ['./layer-values.component.scss']
})
export class LayerValuesComponent implements OnInit, AfterViewInit {

  @ViewChild('layerValues') containerRef: ElementRef;
  offsetX$ = 0;
  offsetY$ = 0;
  lonlat$ = "";
  wkt$ = "";
  layerValues$: Observable<Array<ILayervalue>> = this.store.select(mapReducers.selectGetLayerValues);
  enabled$: Observable<boolean> = this.store.select(mapReducers.selectGetLayerValuesEnabled);
  wktFormat$: WKT;

  constructor(private store: Store<mapReducers.State>, private map: MapComponent, private clipboardService$: ClipboardService) {
    this.wktFormat$ = new WKT();
  }

  ngOnInit(): void {

  }

  moveEndSubject = new Subject<any>();

  ngAfterViewInit(): void {
    this.offsetY$ = this.containerRef.nativeElement.offsetTop;
    this.offsetX$ = this.containerRef.nativeElement.offsetLeft;
    this.map.instance.on('moveend', () => {
      this.moveEndSubject.next({});
    });
    this.moveEndSubject.pipe(throttle(ev => interval(100))).subscribe(() => this.updateValuesLocation());
  }

  updateValuesLocation() {
    const xy = this.map.instance.getCoordinateFromPixel([this.offsetX$, this.offsetY$])
    const lonlat = toLonLat(xy);
    this.wkt$ = this.wktFormat$.writeGeometry(new Point(lonlat))
    this.lonlat$ = toStringHDMS(lonlat);
    this.store.dispatch(new mapActions.SetLayerValuesLocation(xy[0], xy[1]));
  }

  copyToClipboard() {
    this.clipboardService$.copy(this.wkt$);
  }

  public getScaledValue(layerValue: ILayervalue): number {
    let v = layerValue.value;
    if (layerValue.scale && layerValue.scale != 0) {
      v = layerValue.scale * layerValue.value;
    }
    return v;
  }
}
