import { ActivatedRoute, Router } 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, 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[] = [];


  listAssets: any;
  error:boolean;
  listOrganizations: any;
  plantId: string;
  plant: any;
  sub: any;
  plantNotFound: boolean;
  selectedPlant: any;
  meterKeys:any;
  meterKeys2:any;
  assetKeys:any;

  sumarize:number = 0;

  totalMetersInstalled: string;

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

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

  // 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: 10,
    center: latLng([13.661714, -89.251530])
  };

  constructor(
    private plantsService: PlantsService,
    private route: ActivatedRoute,
    private orgService: OrganizationsService,
    private router: Router,
    private zone: NgZone) {

    Swal.fire({
      allowOutsideClick: false,
      type: 'info',
      text: 'Espere por favor...'
    });
    Swal.showLoading();
    
    this.plantsService.getAllAssets().subscribe(res => {
      this.listAssets = res["data"]["assets"];
      this.assetKeys = Object.keys(this.listAssets);
      for (let prop in this.assetKeys){
        this.meterKeys2 = Object.keys(this.listAssets.map(item => item["meters_installed"])[prop]);
        for (let prop2 in this.meterKeys2){
          this.sumarize += this.listAssets.map(item => item["meters_installed"])[prop].map(response => response["installedCapacity_kW"])[prop2];
          //this.totalMetersInstalled = this.sumarize.toString();
          //localStorage.setItem("installedCapacityTotal_kW", this.totalMetersInstalled);
        }
      }      
    }, (err) => {
      Swal.fire({
        type: 'error',
        title: 'Error en el servidor',
        text: "No su pudo obtener la informacion"
      });
    });
  
  }

  ngOnInit(): void {

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

    setTimeout(() => {

      if (this.listAssets != undefined) {
        this.addMarkers();
      }

      Swal.close();
    }, 2700);

  }

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


  addMarkers() {
    let lat, long, address, name2;

    for (const plant of this.listAssets) {
      if (localStorage.getItem("email") == "inverlec@grupomerelec.com") {
        lat = "13.6613819";
        long = "-89.2514334";
        address = "Urbanización Madre Selva Calle Llama del Bosque, Edificio Avante, Local 4-5/4-6, Antiguo Cuscatlán";
        name2 = "Inversiones MERELEC S.A de C.V";
      }
      else {
        lat = plant["meters_installed"][0].gpsLat;
        long = plant["meters_installed"][0].gpsLong;
        address = plant.address;
        name2 = plant.name;
      }

      const newMarker = marker(
        [lat, long],
        { icon: this.icon })
        .bindPopup('<b>' + name2 + '</b><br>Dirección: ' + 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;
    if (localStorage.getItem("email") == "inverlec@grupomerelec.com") {
      this.selectedPlant = {
        name: "Inversiones MERELEC S.A de C.V",
        country: "El Salvador",
        city: "La Libertad",
        address: "Urbanización Madre Selva Calle Llama del Bosque, Edificio Avante, Local 4-5/4-6, Antiguo Cuscatlán",
        installedCapacity_kW: 300
      }
    }
    else {
      this.selectedPlant = this.listAssets.find(e => e.id === this.plantId);
    }
  }

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

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

  goToAsset(id: string) {
    this.router.navigate(['/assets'], { queryParams: { id: id } });
  }


}
