import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ContactService } from '../contact.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-route-map-add',
  templateUrl: './route-map-add.component.html',
  styleUrls: ['./route-map-add.component.scss']
})
export class RouteMapAddComponent implements OnInit {
  grpName: any;
  before:any;
  logoutbut:boolean;
  cust:boolean=false;
  logo:any;
  text:any;
  fs:any;ls:any;emailid:any;or:any;useridd:any;mb:any;custtype:any;dealer:any;
  showImage:any;
  groups=[];
  group_info:any;
  myInput:any;
  deviceId:any;
  device_update:any;
  superAdmin:Boolean = false;
  route_detail_show=[];
  route:any;
  route_1:any;
  Fromdate=new Date();
  todate=new Date();
  routeRadius:any;
  driverName:any;
  Load:any;
  lrNumber:any;
  grp:any;loading:any;unloading:any;
  oneWayTrip:any;
  roundTrip:any;
  allow_reverse:any;
  startDate= new Date();
  endDate= new Date();
  tripForm:FormGroup;
  devices=[]
  Device_Name: any;
  routeName: any;
  constructor(private router: Router,private fb:FormBuilder,private contactService: ContactService,private _flashMessagesService: FlashMessagesService) { 
  
  }



  ngOnInit() {

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

    
    this.logo=window.localStorage['logo'];
    this.text=window.localStorage['text'];  
    window.localStorage['DataUpdate'] = 'Tthis.rue'
     
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    
    
    this.fs = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).fn;
    this.ls = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).ln;
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
     this.mb =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).phn;
     
     this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
     //  console.log('testing',this.useridd);
     if(this.custtype == true){
       this.cust = true;
      }  
      
      if(this.mb.charAt(0)=="n"){
        this.mb = ' '
      }
      if( window.localStorage['Custumer'] == 'ON'){
        this.logoutbut = false
        this.dealer = true
      }
      else{
        this.logoutbut = true
      }
      
      this.getVehicles()
      
  this.getRouteMap();
  this.getGrp();
  this.getDriverDetail();
       this.contactService.getallgeofence(this.useridd)
    .subscribe(res=>{
      this.geofenceName =res;
      // console.log(res);
    })

  }

  mydealer(){
    // console.log('Dealer')
  }

  myaccount(){
    this.cond = false
    this.router.navigateByUrl("accountSettings");
  }

  geo(){
    this.router.navigateByUrl("geofencing");
    
  }


	 Ddetail(){
    this.router.navigateByUrl("driverdetail");
  }
  DModel(){
    this.router.navigateByUrl("deviceModel");
  }
  VType(){
    this.router.navigateByUrl("VehicleType");
  }
  
  openNav() {
    /*  document.getElementById("myNav").style.width = "100%";
  */
     this.router.navigateByUrl("location");
  
  }

  logout(){
    window.localStorage.clear();
    this.router.navigateByUrl("login");
  }
  devi(){
    this.router.navigateByUrl("dashboard");
  
  }
  soon(){
    this.router.navigateByUrl("const?_i="+window.localStorage.token);
    
  }
  new(){
    this.router.navigateByUrl("new");
    
  }
  
  group(){
    this.cond = false
    this.router.navigateByUrl("group_view");
  }

  cond:Boolean = false;
point : any = 0;
 aa(){
  // console.log(this.point);
   if(this.point == 0){
    this.cond = true;
    this.point ++;
   }
 else if(this.point % 2 == 0){
  this.cond = true;
  this.point ++;
 }
 else{
   this.cond = false
   this.point ++;
 }

  
}


report(){
  this.cond = false
  this.router.navigateByUrl("device-report");

}
routeViolation(){
  this.cond = false
  this.router.navigateByUrl("device-report/routeViolation");

}
report_speed(){
  // console.log("report speed call")
  this.cond = false
  this.router.navigateByUrl("device-report/device-speed-report");
}

vehicleRoute(){
  this.cond = false
  this.router.navigateByUrl("vehicleRoute");
}

driverPerformance(){
  this.cond = false
  this.router.navigateByUrl("device-report/Driver-performance");
}

alert_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/alert-report");

}

summaryReport(){

  this.cond = false
  this.router.navigateByUrl("device-report/summary-report");
}

overspeed(){
  this.cond = false
  this.router.navigateByUrl("device-report/overspeed");

}
stoppage_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/stoppage_report");

}

route_map(){
  this.router.navigateByUrl("routeMapping");

}

ignition_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/ignition_report");


}

geofancingReport(){
  this.cond = false
  this.router.navigateByUrl("device-report/geofancing");
}






distance_report(){
this.cond = false
this.router.navigateByUrl("device-report/distance_report");
}

trip_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/trip_report");

}


addRoute(){
  this.cond = false
  this.router.navigateByUrl("setRoute");
}

saveRoute(){
  this.cond = false
  this.router.navigateByUrl('vehicleRoute');
}


addcus(){
  localStorage.removeItem('mapLoad_ID')
  this.router.navigateByUrl("add");
}

dealerInfo(){
  this.cond = false
  this.router.navigateByUrl("dealerInfo");
}


addRouteMap(){
  this.cond = false
  this.router.navigateByUrl("addRouteMap");

}

notification(){
  this.cond = false
  this.router.navigateByUrl("notifications");
}

// Route map method

getRouteMap(){
  // console.log("Mapping history !!!");
  this.contactService.getRouteDetail(this.useridd)
  .subscribe(res=>{
    // console.log("routedet",res);
    this.route_detail_show=res;
  })
  
}


// get group method 
getGrp(){
  this.contactService.getGroup(this.useridd).subscribe(      
    res => {
      // console.log(res);     
      this.grpName = res["group_details"];
      // console.log(this.grpName);  
    })
}



driver:any;
getDriverDetail(){
 
  this.contactService.getRouteDriver(this.useridd)
  .subscribe(res=>{
    this.driver=res;
    // console.log("abcd",this.driver);
   
  })
}

deviceName:any;
geofenceName:any;
groupId:any;
getDevName(grpId){
  var grpVehiclePayload= grpId._id;
  this.groupId = grpVehiclePayload;

  this.contactService.getVehDetail(grpVehiclePayload)
    .subscribe(res=>{
      this.deviceName = res;
      // console.log(this.deviceName);
   
    })

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


round_trip:boolean;
saveMap(){
//  console.log(this.allow_reverse);
//  if(this.allow_reverse==1){
//   this.round_trip=false;
//  }else if (this.allow_reverse==2){
//    this.round_trip=true;
//  }
 
 var startTime = this.Fromdate.getTime();
 var endTime = this.todate.getTime();

 if(this.route == undefined)
 {
   
  this._flashMessagesService.show('Error : Please select route', { cssClass: 'alert-danger', timeout: 2000 });
  
 }else if(this.grp==undefined){
  this._flashMessagesService.show('Error : Please select group', { cssClass: 'alert-danger', timeout: 2000 });
  
 }else if(this.route_1==undefined){
  this._flashMessagesService.show('Error : Please select Device', { cssClass: 'alert-danger', timeout: 2000 });
  
 }else if((this.routeRadius==undefined)||(this.routeRadius==null)){
  this._flashMessagesService.show('Error : Radius is mendatory', { cssClass: 'alert-danger', timeout: 2000 });
  
 }
//  else if(this.driverName==undefined){
//   this._flashMessagesService.show('Error : Please select driver name', { cssClass: 'alert-danger', timeout: 2000 });
  
//  }
 else if(startTime>endTime){
  this._flashMessagesService.show('Error : Start date should not greater than end date', { cssClass: 'alert-danger', timeout: 2000 });
 }else if(this.loading == undefined){
  this._flashMessagesService.show('Error : Please select loading', { cssClass: 'alert-danger', timeout: 2000 });
 }else if(this.unloading == undefined){
  this._flashMessagesService.show('Error : Please select unloading', { cssClass: 'alert-danger', timeout: 2000 });
 }else if(this.allow_reverse==undefined){
  this._flashMessagesService.show('Error : Please select trip', { cssClass: 'alert-danger', timeout: 2000 });
 }else{

  var all_rev = 0;
  all_rev = this.allow_reverse
  var routeMapadd = {
  "route": this.route._id,
  "device":this.route_1._id,
  "radius" : this.routeRadius,
  "user": this.useridd,
  "expiresOn":this.todate,
  "tripType": all_rev,
  "routeName" : this.route.name,
  "deviceName" :this.route_1.Device_Name,
  "poi":[],
  "vehicleGroup":this.groupId,
  "startsOn":this.Fromdate,
 
  "startSite": this.loading._id,
  "endSite" : this.unloading._id
 }

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

 if(this.driverName){
  routeMapadd['driver'] = this.driverName._id;
}


    this.contactService.addRouteMap(routeMapadd)
      .subscribe(res=>{
        // console.log(res);
        this._flashMessagesService.show('Trip route saved', { cssClass: 'alert-success', timeout: 2000 });
      },err=>{   
        if(err.status == 400){
       
          var a = JSON.parse(err._body);
          var b = a.message;
          this._flashMessagesService.show(b, { cssClass: 'alert-success', timeout: 2000 });
        }  
     
        if(err.status ==500){
          this._flashMessagesService.show('Error : Internal server error, Please try after sometime', { cssClass: 'alert-danger', timeout: 2000 });
        }
      })
 }
}

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

  
}

Submit(){
  console.log(this.tripForm.value.vehicleName);
  
  if(this.tripForm.value.vehicleName=="" || this.tripForm.value.vehicleName==undefined){
    this._flashMessagesService.show('Error : Please select Device', { cssClass: 'alert-danger', timeout: 2000 });
    
  }else if(this.tripForm.value.startTime==undefined || this.tripForm.value.startTime==""){
      this._flashMessagesService.show('Error : Please Select Start Time', { cssClass: 'alert-danger', timeout: 2000 });
  } 
  else if(this.tripForm.value.endTime==undefined || this.tripForm.value.endTime==""){
      this._flashMessagesService.show('Error : Please select End Time', { cssClass: 'alert-danger', timeout: 2000 });
  }
  
  else if(startTime>endTime){
    this._flashMessagesService.show('Error : Start date should not greater than end date', { cssClass: 'alert-danger', timeout: 2000 });
  }if(this.tripForm.value.allow_reverse==undefined ||this.tripForm.value.allow_reverse==""){
    this._flashMessagesService.show('Error : Please select trip', { cssClass: 'alert-danger', timeout: 2000 });
  }else{
    
    var startTime = this.tripForm.value.startTime.getTime();
    var endTime = this.tripForm.value.endTime.getTime();
  var all_rev = 0;
  all_rev = this.allow_reverse;
  for(var i=0;i<this.devices.length;i++){
    if(this.tripForm.value.vehicleName==this.devices[i]._id){
      this.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){
      this.routeName=this.route_detail_show[i].name
    }
  }

  var routeMapadd = {
  // "route": this.tripForm.value.routeName,
  "device":this.tripForm.value.vehicleName,
  // "radius" : this.routeRadius,
  "user": this.useridd,
  "expiresOn":this.tripForm.value.endTime,
  "tripType": this.tripForm.value.allow_reverse,
  "routeName" : this.routeName,
  "deviceName" :this.Device_Name,
  "poi":[],
  // "vehicleGroup":this.groupId,
  "startsOn":this.tripForm.value.startTime,
 
  // "startSite": this.loading._id,
  // "endSite" : this.unloading._id
 }
  if(this.tripForm.value.routeName){
   routeMapadd['route'] = this.tripForm.value.routeName;
   routeMapadd['routeName'] = this.routeName
 }
 if(this.tripForm.value.loadingSite){
   routeMapadd['startSite'] = this.tripForm.value.loadingSite
 }

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

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

 if(this.tripForm.value.driverName){
  routeMapadd['driver'] = this.tripForm.value.driverName
}

 console.log('Allow reverse',routeMapadd);
    this.contactService.addRouteMap(routeMapadd)
      .subscribe(res=>{
        // console.log(res);
        this._flashMessagesService.show('Trip route saved', { cssClass: 'alert-success', timeout: 2000 });
        this.router.navigateByUrl('routeMapping');
      },err=>{   
        if(err.status == 400){
       
          var a = JSON.parse(err._body);
          var b = a.message;
          this._flashMessagesService.show(b, { cssClass: 'alert-success', timeout: 2000 });
        }  
     
        if(err.status ==500){
          this._flashMessagesService.show('Error : Internal server error, Please try after sometime', { cssClass: 'alert-danger', timeout: 2000 });
        }
      })
 }
  
}

}
