import { Injectable } from '@angular/core';
import { LocationCommanService } from './service/location-comman.service';

declare var maplibregl: any;
@Injectable()
export class MoveMarkerService {

  forceStopMarkerMove = false;
  constructor(private _locationCommanService: LocationCommanService) { }
  animatedMove(marker, current, moveto,map:any = {},isCenterMap) {
    this.forceStopMarkerMove =false;
    const markerId = marker.id;
    let localMarker = {
      lat:current.lat,
      lng:current.lng
    }
    
    let deltalat = (moveto.lat - current.lat) / 500;
    let deltalng = (moveto.long - current.lng) / 500;
    let i = 0;
    let that = this;
    function moveItSelf(){
      setTimeout(function () {
        let lat = localMarker.lat;
        let lng = localMarker.lng;
        lat += deltalat;
        lng += deltalng;
        //let latlng = new google.maps.LatLng(lat, lng);
        localMarker.lat = lat;
        localMarker.lng = lng;
        if(isCenterMap && map) {
          if(!map.getBounds().contains(marker.marker.getLngLat())) {
            map.setCenter([localMarker.lng,localMarker.lat])
          }
        } 
        marker.marker.setLngLat([localMarker.lng,localMarker.lat])
         
        
        if(i<500 && marker.id == markerId && !that.forceStopMarkerMove) {
          i++;
          moveItSelf();
        } else {
         
        }
      }, 10);
    }
    moveItSelf();
    
  }


  animatedMarker(historyData,map,cordinates) {
    if(cordinates) {
      
    historyData.markerId = 'marker_'+(new Date()).getTime();
    if(historyData && historyData.currentPath) {
      let device = historyData.currentPath.device_obj;
      //let cordinates = historyData.currentPath.dataArrayCoords && historyData.currentPath.dataArrayCoords.length ? historyData.currentPath.dataArrayCoords[0] : [0,0]
    
    const marker = {
      'type': 'Feature',
      'properties': {
        'message': 'Not found',
        'iconSize': [48, 48]
      },
      'geometry': {
        'type': 'Point',
        'coordinates': [27.51, 77.01]
      }
    };
    if (device.iconType == 'bus') {
      marker.properties.iconSize = [25, 48];
    }
    marker.properties.message = device.Device_Name;
    marker.geometry.coordinates = cordinates;
    let url = this._locationCommanService.iconSelector('RUNNING', device.iconType);
    const el = document.createElement('div');
    const width = marker.properties.iconSize[0];
    const height = marker.properties.iconSize[1];

    const elImg = document.createElement('div');
    
    el.className = 'marker';
    elImg.style.backgroundImage = `url(${url})`;
    el.style.width = `${width}px`;
    el.style.height = `${height}px`;
    el.classList.add('marker-map-section');
    elImg.classList.add('marker-mapi-section');
    el.style.backgroundSize = '100%';

    let rotationDegree = this.roatedImage(device.heading)
    elImg.id =  historyData.markerId;
   elImg.style.transform = `rotateZ(${rotationDegree}deg)`;
    el.appendChild(elImg);
    //el.rotation = 
    el.addEventListener('click', () => {

    });
    historyData.vehicleMarker = new maplibregl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    //.setRotation(rotationDegree)
  
    // .setRotation(rotationDegree)
    .addTo(map);

      
  }
    }

  }
  removeAllStoppage(stoppages){
    if(stoppages.displayMarkers && stoppages.displayMarkers.length) {
      stoppages.displayMarkers.forEach(item => {
        item.remove();
      });
      stoppages.displayMarkers = [];
    }
  }
  stoppageMarker(map,markerData,stoppages) {
    this.removeAllStoppage(stoppages);
    markerData.forEach(marker=>{
      let pContent :any= {};
      pContent.latitude = marker[0];
      pContent.longitude = marker[1];
      pContent.arrivalTime = new Date(marker[2]).toLocaleString();
      pContent.departureTime = new Date(marker[3]).toLocaleString();
      pContent.addresslocation = marker[4];
    
      let fd = new Date(pContent.arrivalTime).getTime();
      let td = new Date(pContent.departureTime).getTime();
      let time_difference = td - fd;
      let total_min = time_difference / 60000;
      let hours = total_min / 60
      let rhours = Math.floor(hours);
      let minutes = (hours - rhours) * 60;
      let rminutes = Math.round(minutes);
      pContent.Durations = rhours + ':' + rminutes
      let content = '<div><div> Arrival Time-: '
          + pContent.arrivalTime + '</div><br><div>Departure Time-: '
          + pContent.departureTime + '</div><br><div>Time Duration-: '
          + pContent.Durations + ' </div></br><div> Latitude-: '
          + pContent.latitude + ' </div></br><div> Longitude-: '
          + pContent.longitude + ' </div><br></div>'
      let popup = new maplibregl.Popup({ offset: 25 }).setHTML(content).setMaxWidth("200px");
      let markerInstance = new maplibregl.Marker({
        color: 'blue'
        })
        .setLngLat([marker[1],marker[0]])
        .setPopup(popup)
        .addTo(map);
        stoppages.displayMarkers.push(markerInstance);
    })

      
  

  }
  roatedImage(degree, minus = 0) {
    return (degree ? degree - minus : 0) * Math.PI / 180;

  }
  animatedMoveWithSelf(marker, current, moveto,speed=1,callback) {
    
    
    // if(current.lat == moveto.lat && current.lng == moveto.lng) {
    //   callback('done')
    // } else {
      const defaultSpeed = 300;
      let markerSpeed = defaultSpeed/speed;
    
    
      let localMarker = {
        lat:current.lat,
        lng:current.lng
      }
      
      let deltalat = (moveto.lat - current.lat) / markerSpeed;
      let deltalng = (moveto.lng - current.lng) / markerSpeed;
      let i = 0;
      let moveItSelf = ()=>{
        setTimeout(function () {
          let lat = localMarker.lat;
          let lng = localMarker.lng;
          lat += deltalat;
          lng += deltalng;
          //let latlng = new google.maps.LatLng(lat, lng);
          localMarker.lat = lat;
          localMarker.lng = lng;
          marker.setLngLat([localMarker.lng,localMarker.lat])
          if(i<markerSpeed) {
            i++;
            moveItSelf();
          } else {
           callback('done');
          }
        }, 10);
      }
      moveItSelf();
    }
    
  


}
