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

import { of as observableOf, Observable, throwError, from } from 'rxjs';

import * as moment from 'moment';
import Swal from 'sweetalert2';


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

  title = "Dashboard";


  listData:any;
  rows = [];
  markers: Layer[] = [];
  points: LatLng[] = [];

  listOrganizations: any;
  error:boolean;
  plantId: string;
  plant:any;
  sub: any;
  plantNotFound: boolean;
  selectedPlant: any;


  totalMetersInstalled:string;

  lastUpdate = new Date().toLocaleString();
  i: number;

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

  // Open Street Map definitions
  LAYER_OSM = tileLayer(
    'http://{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])
  };
  
  constructor(private plantsService: PlantsService, private route: ActivatedRoute, private orgService: OrganizationsService, private zone: NgZone) {

    Swal.fire({
      allowOutsideClick: false,
      type: 'info',
      text: 'Espere por favor...'
    });
    Swal.showLoading();


    this.plantsService.getAssets().subscribe(res => {
      this.listData = res["assets"];
    }, (err) => {
      Swal.fire({
        type: 'error',
        title: 'Error en el servidor',
        text: "No su pudo obtener la informacion"
      });
    });

    if (localStorage.getItem("installedCapacityTotal_kW") == undefined){
      this.plantsService.getInstalledCapacity().subscribe(res => {
        this.totalMetersInstalled = res["installedCapacityTotal_kW"];
        localStorage.setItem("totalMetersInstalled", this.totalMetersInstalled);
      });
    }
    else {
      this.totalMetersInstalled = localStorage.getItem("installedCapacityTotal_kW");
    }
    
  
  }


  ngOnInit(): void {

    setTimeout(()=>{ 
      this.addMarkers();
      Swal.close();
    }, 1500);

    
    var responsiveOptions: any[] = [
      ['screen and (max-width: 640px)', {
        seriesBarDistance: 5,
        axisX: {
          labelInterpolationFnc: function (value) {
            return value[0];
          }
        }
      }]
    ];

  }

  getAsset(id:string){
    return observableOf(this.listData.find(e => e.id === id));
  }

  
  addMarkers() {
    for (const plant of this.listData) {
      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: string) {
    this.plantId = id;
    this.selectedPlant = this.listData.find(e => e.id === this.plantId);
    console.log("selected plant");
    console.log(this.selectedPlant);
  }

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

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


}
