import { Component, OnInit, Inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../contact.service';
declare var _ :any;
@Component({
  selector: 'app-edit-route-map',
  templateUrl: './edit-route-map.component.html',
  styleUrls: ['./edit-route-map.component.scss']
})
export class EditRouteMapComponent implements OnInit {
  deviceName:any;
  tripDetails: any;
  geofenceName: any;
  grpName: any;
  lrNumber:any;
  tripForm:FormGroup
  
  emailid:any;or:any;useridd:any;
  devices=[]
  groups=[];
  group_info:any;
  myInput:any;
  deviceId:any;
  device_update:any;
 
  route_detail_show=[];
  route:any;
  route_1:any;
  Fromdate=new Date();
  todate=new Date();
  routeRadius:any;
  driverName:any;
  Load:any;
  grp:any;loading:any;unloading:any;
  oneWayTrip:any;
  roundTrip:any;
  allow_reverse:any;
  startDate= new Date();
  endDate= new Date();
  route_edit: any;
  routeObject: { name: any; _id: any; };
  selectedvalue:any;
  vehicleObj: { name: any; _id: any; };
  veh_edit: any;
  vehicleValue: any;
  driverDetail:any;
  driverObj: { name: any; _id: any; };
  vehicleGroup: any;
  existingGrp:any;
  grpObj: { name: string; _id: string; };
  geofenceObj: any;
  geofenceload:any;
  geofenceUnload:any;
  selectedValue1: any;
  constructor(private contactService: ContactService,private fb:FormBuilder,public dialogRef: MdDialogRef<EditRouteMapComponent>,
    @Inject(MD_DIALOG_DATA) public data: any) {



    this.tripDetails = data;
    console.log("DATA=====",this.tripDetails);
    
    this.geofenceload = {
      name:this.tripDetails.routeId.Loading_Site,
      _id:this.tripDetails.routeId.Loading_Site_Id
    }

    this.geofenceUnload={
      name:this.tripDetails.routeId.Unloading_Site,
      _id:this.tripDetails.routeId.Unloading_Site_Id
    }

    // console.log('geofencePayload',this.geofenceUnload)
    // this.vehicleGroup =data.vehicleGroup;
        // console.log("mainPayload",this.tripDetails)
    this.existingGrp = {
      name : this.tripDetails.routeId.VehicleGroup_Name,
      _id:this.tripDetails.routeId.VehicleGroup_Id
    }


    this.getDevName(this.existingGrp._id);

    // console.log('checking grp',this.existingGrp._id);
    
    this.route_edit=
    {
      name:this.tripDetails.routeId.Route_Name,
      _id:this.tripDetails.routeId.Route_Id
    }
    this.selectedvalue=_.cloneDeep(this.route_edit);

    this.veh_edit={
      name:this.tripDetails.routeId.Device_Name,
      _id:this.tripDetails.routeId.Device_Id
    }

    this.selectedValue1 = _.cloneDeep(this.veh_edit);
    // console.log("datafrompreCOmponent",this.veh_edit)
    this.driverDetail={
      name:this.tripDetails.routeId.Driver,
      _id:this.tripDetails.routeId.Driver_Id
      
    }


    this.Fromdate = new Date(this.tripDetails.routeId.Planned_Start_Time);
    this.todate = new Date(this.tripDetails.routeId.Planned_End_Time);


    // this.vehicleValue = _.cloneDeep(this.veh_edit);


    // console.log('this.selectedvalue',this.selectedvalue);
    // console.log('this.vehvalue',this.vehicleValue)
    // console.log('thisiskey',this.route_edit)
    this.routeRadius = this.tripDetails.routeId.Radius;
    this.allow_reverse=this.tripDetails.routeId.Allow_Reverse;
    //  console.log("nameofroute",this.allow_reverse);
      this.allow_reverse = this.allow_reverse?"2":"1";
     }

  ngOnInit() {
     this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.getRouteMap();
    this.getGrp();
//     Allow_Reverse: false
// Device_Id: "2049080054708"
// Device_Name: "siwitest"
// Planned_End_Time: "2021-09-07T14:57:27.640Z"
// Planned_Start_Time: "2021-09-07T14:57:27.640Z"
// Radius: 200
// Status: "ASSIGNED"
// deviceObjId: "612f33fa9e94de2c84f8278a"
// lrNumber: "0004343"
// routeId: "61377dee12c0622dc4465aa2"
// total_odo: 0
// tripType: 1

    this.getDriverDetail();
      this.tripForm=this.fb.group({
      routeName:[''],
      vehicleName:[''],
      driverName:[''],
      loadingSite:[''],
      unloadingSite:[''],
      startTime:[''],
      endTime:[''],
      lrNumber:[''],
      allow_reverse:['']
    })

    this.getVehicles();
    this.patchValues()
    this.contactService.getallgeofence(this.useridd)
    .subscribe(res=>{
      this.geofenceName =res;
      // console.log(res);
    })
  }

  patchValues(){
    this.tripForm.patchValue({
       routeName:this.tripDetails.routeId.Route_Id?this.tripDetails.routeId.Route_Id:'',
      vehicleName:this.tripDetails.routeId.deviceObjId?this.tripDetails.routeId.deviceObjId:'',
      driverName:'',
      loadingSite:this.tripDetails.routeId.Loading_Site_Id?this.tripDetails.routeId.Loading_Site_Id:undefined,
      unloadingSite:this.tripDetails.routeId.Unloading_Site_Id?this.tripDetails.routeId.Unloading_Site_Id:undefined,
      startTime:this.tripDetails.routeId.Planned_Start_Time?this.tripDetails.routeId.Planned_Start_Time:'',
      endTime:this.tripDetails.routeId.Planned_End_Time?this.tripDetails.routeId.Planned_End_Time:'',
      lrNumber:this.tripDetails.routeId.lrNumber?this.tripDetails.routeId.lrNumber:'',
      allow_reverse:this.tripDetails.routeId.tripType?'2':'1'
    })
  } 


  driver: any;
  driverArr=[]
  getDriverDetail() {
  
    this.driverArr=[];
    this.contactService.getRouteDriver(this.useridd)
      .subscribe(res => {
        this.driver = res;
        // console.log("abcd", this.driver);
        for(var i=0;i<this.driver.length;i++){
          this.driverObj={
            name:this.driver[i].name,
            _id:this.driver[i]._id
          }

          this.driverArr.push(this.driverObj);
        }

      })
  }

  grpArr=[];

  getGrp(){
    this.grpArr=[];
    this.contactService.getGroup(this.useridd).subscribe(      
      res => {
        // console.log(res);     
        this.grpName = res["group_details"];
        // console.log('grpobj',this.grpName);
        if(this.grpName){
          for(var i=0;i<this.grpName.length;i++){
            this.grpObj={
              name:this.grpName[i].name,
              _id:this.grpName[i]._id
            }
              this.grpArr.push(this.grpObj);
          }
        }
     
        // console.log('finalgrppayload',this.grpArr);  
      })
  }

  routeNameArr=[];
  getRouteMap(){
    this.routeNameArr=[];
    // console.log("Mapping history !!!");
    this.contactService.getRouteDetail(this.useridd)
    .subscribe(res=>{
      // console.log("routedet",res);
      this.route_detail_show=res;
      let temp =[];
      for(var i=0;i<this.route_detail_show.length;i++){
            this.routeObject={
              name:this.route_detail_show[i].name,
              _id:this.route_detail_show[i]._id
            }
            
            temp.push(this.routeObject);
      }
      this.routeNameArr=_.cloneDeep(temp);
  
    })

    // console.log("newObj",this.routeNameArr);
  }

vehArr=[];
  getDevName(grpId){
  // console.log('groupId',grpId);
  var grpVehiclePayload= grpId;
  this.geofenceObj=[];
  this.vehArr=[];
  var temp1 = [];
  this.contactService.getVehDetail(grpVehiclePayload)
    .subscribe(res=>{
      this.deviceName = res;
      // console.log('deviceName',this.deviceName);
      let tempVeh=[];
      for(var i=0;i<this.deviceName.length;i++){
        this.vehicleObj={
          name:this.deviceName[i].Device_Name,
          _id:this.deviceName[i]._id
        }
        
        temp1.push(this.vehicleObj);
      }



       this.vehArr = _.cloneDeep(temp1);
      //  console.log('vehicleDetails',this.vehArr);
    })

   this.contactService.getLoadUnload(grpVehiclePayload)
    .subscribe(res=>{
      this.geofenceName =res;
      // console.log("geofenceval",this.geofenceName);

      for(var i=0;i<this.geofenceName.length;i++){
        var loadingObj={
          name:this.geofenceName[i].geoname,
          _id:this.geofenceName[i]._id
         
        }
        this.geofenceObj.push(loadingObj);

      }
     
        // console.log('geofencedata',this.geofenceObj);
    })
}



editDetails(){

  var outerThis =this;   
     let data =  _.find(this.routeNameArr, function(o) { 
        if(o._id == outerThis.selectedvalue._id){
          return o;
        } 
      });
      // console.log("data=",data.name);
 

      let vehData =  _.find(this.vehArr, function(v) { 
        if(v._id == outerThis.selectedValue1._id){
          return v;
        } 
      });
        // console.log("vehData=",vehData.name);
      // console.log('vehData=',vehData);
      // console.log("PlannedStartTime",this.Fromdate);
      // console.log("PlannedEndTime",this.todate);
      // console.log('allowReverse',this.allow_reverse);
      // console.log("DriverId",this.driverDetail._id);
      // console.log("vehicleID",this.veh_edit._id)
      // console.log("loadingId",this.geofenceload._id);
      // console.log("unloading",this.geofenceUnload._id);
      var tripVal;
      if(this.allow_reverse=="2"){
        tripVal = true;
      }else{
        tripVal = false;
      }
      // console.log("allowRevVal",tripVal);

      // console.log('vehicleID=>',this.veh_edit._id);
       var tripUpdateObj={
            "_id":this.tripDetails.routeId.routeId,
            "route" : data._id,    
            "device" :this.veh_edit._id,
            "radius" :this.routeRadius,
            "user" : this.useridd,
            "startsOn" :new Date(this.Fromdate),
            "expiresOn" :new Date(this.todate),
            "allowReverse" :tripVal,
            "routeName" :data.name,
            "deviceName":vehData.name,
            "driver":this.driverDetail._id,
            "startSite":this.geofenceload._id,
            "endSite":this.geofenceUnload._id,
          
        }

        if(this.lrNumber){
          tripUpdateObj['lrNumber'] =  this.lrNumber;
        }

      // console.log("finaltripobjPayload",tripUpdateObj);

      this.contactService.updateRouteMap(tripUpdateObj)
        .subscribe(res=>{
          // console.log(res);
          this.dialogRef.close("success");
        })
    
}

onCloseCancel(){
  // console.log("cancel button clicked");
  this.dialogRef.close('Cancel');
}
  // http://localhost:3000/trackRoute/5b1e54b2aa6dde281abf04c3


  changeRouteName(event){
    // console.log(event);
  }

  Submit(){
    console.log(this.tripForm.value);
    var Device_Name,routeName
    for(var i=0;i<this.devices.length;i++){
    if(this.tripForm.value.vehicleName==this.devices[i]._id){
     Device_Name=this.devices[i].Device_Name
    }
  }

  for(var i=0;i<this.route_detail_show.length;i++){
    if(this.tripForm.value.routeName==this.route_detail_show[i]._id){
      routeName=this.route_detail_show[i].name
    }
  }

     var tripVal;
      if(this.tripForm.value.allow_reverse=="2"){
        tripVal = true;
      }else{
        tripVal = false;
      }
      // console.log("allowRevVal",tripVal);

      // console.log('vehicleID=>',this.veh_edit._id);
       var tripUpdateObj={
            "_id":this.tripDetails.routeId.routeId,
            // "route" : this.tripForm.value.routeName,    
            "device" :this.tripForm.value.vehicleName,
            // "radius" :this.routeRadius,
            "user" : this.useridd,
            "startsOn" :new Date( this.tripForm.value.startTime),
            "expiresOn" :new Date(this.tripForm.value.endTime),
            "allowReverse" :tripVal,
            "routeName" :routeName,
            "deviceName":Device_Name,
            "driver":this.tripForm.value.driverName,
            "startSite":this.tripForm.value.loadingSite,
            "endSite":this.tripForm.value.unloadingSite,
          
        }
        if(this.tripForm.value.routeName){
          tripUpdateObj['route'] =  this.tripForm.value.routeName;
        }

         if(this.tripForm.value.loadingSite){
          tripUpdateObj['startSite'] =  this.tripForm.value.loadingSite;
        }

        if(this.tripForm.value.unloadingSite){
          tripUpdateObj['endSite'] =  this.tripForm.value.unloadingSite;
        }

        if(this.tripForm.value.lrNumber){
          tripUpdateObj['lrNumber'] =  this.tripForm.value.lrNumber;
        }

      console.log("finaltripobjPayload",tripUpdateObj);

      this.contactService.updateRouteMap(tripUpdateObj)
        .subscribe(res=>{
          // console.log(res);
          this.dialogRef.close("success");
        })
  }

  getVehicles(){
  this.contactService.getDevice(this.emailid,this.useridd).subscribe((res:any)=>{
    this.devices=res.devices
  })

  
}

}


