import { Injectable } from '@angular/core';

import * as moment from 'moment-timezone';
import { ContactService } from '../../contact.service';
declare var maplibregl: any;
@Injectable()
export class LocationCommanService {

  constructor(private contactService :ContactService) { }
  iconSelector(status, iconType) {
    var iconUrl = "";
    if (status == "OUT OF REACH") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/obike.png';
        return iconUrl;
      }
      if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/ocar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/obus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/otruck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/otractor.png';
        return iconUrl;
      } else if (iconType == 'jcb') {
        iconUrl = '/assets/images/liveTrackIcons/ourjcb.png';
        return iconUrl;
      }
      else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_b.png';
        return iconUrl;
      }
      else {
        iconUrl = '/assets/images/liveTrackIcons/user_b.png';
        return iconUrl;
      }

    } else if (status == "STOPPED") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/sbike.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/scar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/sbus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/struck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/stractor.png';
        return iconUrl;
      } else if (iconType == 'jcb') {
        iconUrl = '/assets/images/liveTrackIcons/stoppedjcb.png';
        return iconUrl;
      } else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_r.png';
        return iconUrl;
      } else {
        iconUrl = '/assets/images/liveTrackIcons/user_r.png';
        return iconUrl;
      }
    } else if (status == "RUNNING") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/rbike.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/rcar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/rbus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/rtruck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/rtractor.png';
        return iconUrl;
      } else if (iconType == 'jcb') {
        iconUrl = '/assets/images/liveTrackIcons/runningjcb.png';
        return iconUrl;

      } else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_g.png';
        return iconUrl;
      } else {
        iconUrl = '/assets/images/liveTrackIcons/user_g.png';
        return iconUrl;
      }
    } else if (status == "IDLING") {
      if (iconType == 'bike') {
        iconUrl = '/assets/images/liveTrackIcons/ibike.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/images/liveTrackIcons/icar.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/images/liveTrackIcons/ibus.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/images/liveTrackIcons/itruck.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/images/liveTrackIcons/itractor.png';
        return iconUrl;
      } else if (iconType == "jcb") {
        iconUrl = '/assets/images/liveTrackIcons/idlingjcb.png';
        return iconUrl;

      } else if (iconType == 'ambulance') {
        iconUrl = '/assets/images/liveTrackIcons/ambulance_y.png';
        return iconUrl;
      } else {
        iconUrl = '/assets/images/liveTrackIcons/user_y.png';
        return iconUrl;
      }
    } else if (status == "NO DATA") {
      if (iconType == 'bike') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'car') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'bus') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'truck') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'tractor') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else if (iconType == 'jcb') {
        iconUrl = '/assets/image/no_data.png';
        return iconUrl;
      } else {
        iconUrl = '/assets/images/liveTrackIcons/user_g.png';
        return iconUrl;
      }
    }
  }

  getPopupHTML(device: any = {
    Device_Name: '',
    lastUpdate: '',
    gpsTracking: null,
    gsm_signal: '',
    DriverNumber: '',
    DriverName: '',
    last_speed: '',
    status_updated_at: ''
  }) {

    return '<div class="infoB">' +
      '<div class="DeviceHead">' +
      '<button style= "display:none;position: absolute; left: 0; background: #65889c; color: white; margin-left: 5px;" onclick="window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.addpoi(\'' + device.lastLat + ',' + device.lastlong + '\');})"> add poi </button>' +
      '<p style="margin-bottom: 5px;">' + device.Device_Name + '</p>' +
      '</div>' +
      '<div class="row rowTwo">' +
      '<div class="col-sm-5">' +
      "Last updated" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      (device.lastUpdate ? (moment(device.lastUpdate).format('dddd,ll,LTS') + " " + '(' + moment(device.lastUpdate).fromNow() + ')') : "No Data Available") +
      '</div>' +
      '</div>' +
      '<div class="row rowOne">' +
      '<div class="col-sm-5">' +
      "GPS Positioned" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      (device.gpsTracking == '1' ? 'Yes' : (device.gpsTracking == '0' ? 'No' : '<small>Feature not supported by device</small>')) +
      '</div>' +
      '</div>' +
      '<div class="row rowTwo">' +
      '<div class="col-sm-5">' +
      "GPS Signal" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      ((device.gsm_signal != undefined) ? device.gsm_signal : "NA") +
      '</div>' +
      '</div>' +
      '<div class="row rowOne">' +
      '<div class="col-sm-5">' +
      "Driver's Name" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      '<p style="margin-bottom:0px">' + (device.DriverName ? device.DriverName : 'NA') + '</p>' +
      '</div>' +
      '</div>' +
      '<div class="row rowOne">' +
      '<div class="col-sm-5">' +
      "Driver's Number" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      '<p style="margin-bottom:0px">' + (device.DriverNumber ? device.DriverNumber : 'NA') + '</p>' +
      '</div>' +
      '</div>' +
      '<div class="row rowTwo">' +
      '<div class="col-sm-5">' +
      "Last Speed" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      (device.last_speed) + " kmph" +
      '</div>' +
      '</div>' +
      '<div class="row rowOne">' +
      '<div class="col-sm-5">' +
      "Status" +
      '</div>' +
      '<div class="col-sm-7 leftPadding">' +
      '<p style="margin-bottom:0px">' + this.getStatusDuration(device.status_updated_at) + '</p>' +
      '</div>' +
      '</div>'
  }

  getStatusDuration(since) {

    var arrival_time = new Date(since);
    var curr_time = new Date();
    var fd = new Date(arrival_time).getTime();
    var td = curr_time.getTime();
    var timedev_status_difference = td - fd;
    var total_min = timedev_status_difference / 60000;
    var hours = total_min / 60
    var rhours = Math.floor(hours);
    var minutes = (hours - rhours) * 60;
    var rminutes = Math.round(minutes);

    var Durations = rhours + " " + 'hrs' + " " + rminutes + " " + 'min';
    if (since == undefined) {
      return '';

    }

    else {

      if (status == undefined) {

        var status_toShow = "NA";

      } else {
        var status_toShow = status + " " + "Since" + " " + Durations;
      }

      return status_toShow;


    }

  }
  removeSourceById(map, id,isSelf=false) {
    if (map.getLayer(id)) {
      try {
        map.removeLayer(id);
      } catch (error) {

      }
    }
    if (map.getSource(id)) {
      try {
        map.removeSource(id);
      } catch (error) {

      }
    }
    if(!isSelf) {
      this.removeSourceById(map, id + '_points',true);
    }
  }
  removeAllSource(map, flag = "_line") {
    map.getStyle().layers.forEach((layer) => {
      if (layer.id.match(/line_/g)) {
        map.removeLayer(layer.id);
        map.removeSource(layer.id);
      }
    });
  }
  displayLineDraw(map, historyPathId, cordinatesList) {

    //  let cordinates = []; 
    //  cordinatesList.forEach(item=>{
    //   cordinates.push([item[0],item[1]])
    //  } )
    var geojson = {
      'type': 'FeatureCollection',
      'features': [
        {
          'type': 'Feature',
          'properties': {},
          'geometry': {
            'coordinates': cordinatesList,
            'type': 'LineString'
          }
        }
      ]
    };
    map.addSource(historyPathId, {
      type: 'geojson',
      lineMetrics: true,
      data: geojson
    });

    // the layer must be of type 'line'
    map.addLayer({
      type: 'line',
      source: historyPathId,
      id: historyPathId,
      paint: {
        'line-color': 'blue',
        'line-width': 3,
        // 'line-gradient' must be specified using an expression
        // with the special 'line-progress' property

      },
      layout: {
        'line-cap': 'round',
        'line-join': 'round'
      }
    });

  }
  
  calculateHeading(point1, point2){
    function radians_to_degrees(radians)
    {
      var pi = Math.PI;
      return radians * (180/pi);
    }
    let  dLon = (point2.lng - point1.lng);

      let y = Math.sin(dLon) * Math.cos(point2.lat);
      let x = Math.cos(point1.lat) * Math.sin(point2.lat) - Math.sin(point1.lat)
              * Math.cos(point2.lat) * Math.cos(dLon);

      let brng = Math.atan2(y, x);

      brng = radians_to_degrees(brng);
      brng = (brng + 360) % 360;
      brng = 360 - brng; // count degrees counter-clockwise - remove to make clockwise

      return [brng];
    

    // console.log(point1,point2);
    // let dy = point2.lng - point1.lng;
    // let dx = point2.lat - point1.lat;
  
    // let dr = Math.sqrt(dx*dx+dy*dy);
    // if(dy>0)
    //   return [90-Math.acos(dx/dr)*90/Math.PI, dx, dy]
    // return [90+Math.acos(dx/dr)*90/Math.PI, dx, dy]
  }
  displayPoints(map, markerPointsLayerId, list) {
    let poinstArray = [];
    list.forEach(item => {
      let datee = JSON.stringify(item.insertionTime);
      if(!item.latLngKey) {
        item.latLngKey = item.lat+'_'+item.lng
      }
      poinstArray.push({
        'type': 'Feature',
        'properties': {
          'key':item.latLngKey,
        'description': `<div id="content"><div id="bodyContent"><div><br><b>DEVICE NAME : `
        + item.dName + `</b><br><b>IMEI : `
        + item.imei + `</b><br><b>DEVICE DATE : ` 
        + datee + `</b><br><b>SPEED : ` 
        + item.speed +  `Km/hr </b><br><b style="margin-bottom:10px" id="addressBinding">Address : `
         + item.latLngKey  + `</b></div></b></div>
         </div></div>`},
        'geometry': {
        'type': 'Point',
        'coordinates': [item.lng, item.lat]
        }

       
      })
    });
    map.addSource(markerPointsLayerId, {
      'type': 'geojson',
      'data': {
        'type': 'FeatureCollection',
        'features': poinstArray
      }
    });

   

    map.addLayer({
      'id': markerPointsLayerId,
      'type': 'circle',
      'source': markerPointsLayerId,
      'paint': {
        'circle-radius': 5,
        'circle-color': 'blue'
      },
      'filter': ['==', '$type', 'Point']
    });

   

    // When a click event occurs on a feature in the states layer,
    // open a popup at the location of the click, with description
    // HTML from the click event's properties.
    map.on('click', markerPointsLayerId, (e) => {
     
      new maplibregl.Popup()
        .setLngLat(e.lngLat)
        .setHTML(e.features[0].properties.description.replace(e.features[0].properties.key,this.contactService.localAddress[e.features[0].properties.key]))
        .addTo(map);
    });

    // Change the cursor to a pointer when
    // the mouse is over the states layer.
    map.on('mouseenter', markerPointsLayerId, () => {
      map.getCanvas().style.cursor = 'pointer';
    });

    // Change the cursor back to a pointer
    // when it leaves the states layer.
    map.on('mouseleave', markerPointsLayerId, () => {
      map.getCanvas().style.cursor = '';
    });
  }
}
