import { Component, OnInit, NgZone } from '@angular/core';
import { latLng, tileLayer, marker, Layer, icon, Map, latLngBounds, LatLng, LatLngBounds, point } from 'leaflet';
import { Plant } from 'src/app/models/plant';
import { PlantsService } from 'src/app/services/plants.service';

@Component({
  selector: 'app-maps',
  templateUrl: './maps.component.html',
  styleUrls: ['./maps.component.scss']
})
export class MapsComponent implements OnInit {

  listData: any;
  markers: Layer[] = [];
  points: LatLng[] = [];
  plantId: number;

  icon = icon({
    iconSize: [25, 41],
    iconAnchor: [13, 41],
    iconUrl: 'assets/img/marker-icon.png',
    //shadowUrl: 'marker-shadow.png'
  });


  constructor(private plantsService: PlantsService, private zone: NgZone) {
  }

  // Open Street Map definitions
  LAYER_OSM = tileLayer(
    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {
      maxZoom: 18,
      attribution: '&copy; OpenStreetMap contributors'
    });

  // Values to bind to Leaflet Directive
  options = {
    layers: [this.LAYER_OSM],
    zoom: 8,
    center: latLng([13.661714, -89.251530])
  };

  ngOnInit() {
    this.plantsService.getAllAssets().subscribe(res => {
      this.listData = res;
    });
    this.addMarkers();
  }

  addMarkers() {
    for (const plant of this.listData) {
      const name = plant.name;
      const lat = plant.latitud;
      const long = plant.longitud;
      const newMarker = marker(
        [lat, long],
        { icon: this.icon })
        .bindPopup('<b>' + plant.name + '</b><br>Dirección: ' + plant.address)
        .on('click', () => {
          this.zone.run(() => {
            this.sendPlantId(plant.id);
          });
        });
      this.points.push(latLng([lat, long]));
      this.markers.push(newMarker);
    }
  }

  sendPlantId(id: number) {
    this.plantId = id;
  }

  onMapReady(map: Map) {
    setTimeout(() => {
      map.invalidateSize();
    }, 0);

    const bounds = latLngBounds(this.points);
    map.fitBounds(bounds, {
      padding: point(24, 24),
      maxZoom: 10.5,
      animate: true
    });
  }


}
