import { Component, Input, OnDestroy, OnInit, EventEmitter, Output, Inject } from '@angular/core';
import { MapComponent } from '@farmmaps/ng-openlayers';

import * as proj  from 'ol/proj';
import {Point,Geometry} from 'ol/geom';
import { GeoJSON } from 'ol/format';
import { Feature} from 'ol';

export interface IDroppedFile {
  files: any,
  event: any,
  geometry: any
  parentCode: string;
}

@Component({
    selector: 'fm-map-file-drop-target',
    template: '',
    standalone: false
})
export class FileDropTargetComponent implements OnInit, OnDestroy {
  element: Element;
  @Output() onFileDropped = new EventEmitter<IDroppedFile>();
  @Input() parentCode: string;
  @Input() features: Array<Feature<Geometry>>;

  constructor(private map: MapComponent) {
  }

  ngOnInit() {
    this.element = this.map.instance.getViewport();
    const other = this;
    this.element.addEventListener('drop', this.onDrop, false);
    this.element.addEventListener('dragover', this.preventDefault, false);
    this.element.addEventListener('dragenter', this.preventDefault, false);
  }

  private onDrop = (event: DragEvent) => {
    this.stopEvent(event);
    const geojsonFormat = new GeoJSON(); 
    let parentCode = this.parentCode;
    const coordinate = this.map.instance.getEventCoordinate(event);
    //coordinate = proj.transform(coordinate, this.map.instance.getView().getProjection(), 'EPSG:4326');
    let geometry:Geometry = new Point(coordinate);
    const hitFeatures = this.map.instance.getFeaturesAtPixel([event.pageX, event.pageY]);
    const hitFeature = hitFeatures && hitFeatures.length > 0 ? hitFeatures[0] : null;
    if (hitFeature) {
      if (hitFeature.get("code")) {
        parentCode = hitFeature.get("code");
      }
      geometry = geojsonFormat.readGeometry(geojsonFormat.writeGeometry(geometry)); // create copy instead of reference
    }
    const projectedGeometry = geometry.transform(this.map.instance.getView().getProjection(), 'EPSG:4326');   
      
    if (event.dataTransfer && event.dataTransfer.files) {
      this.onFileDropped.emit({ files: event.dataTransfer.files, event: event, geometry: JSON.parse(geojsonFormat.writeGeometry(projectedGeometry)),parentCode:parentCode})
    }
  }
   
  private preventDefault(event) {
    event.preventDefault();
  }

  private stopEvent(event) {
    event.stopPropagation();
    event.preventDefault();
  }

  ngOnDestroy() {
    this.element.removeEventListener('drop', this.onDrop);
    this.element.removeEventListener('dragover', this.preventDefault);
    this.element.removeEventListener('dragenter', this.preventDefault);
  }
}
