import { Component, Inject, OnInit} from '@angular/core';
import {JSONEditor} from 'jsoneditor';
import {Device} from '../device';

import {Driver} from '../driver';
import {Token} from '../token';
import{Contact} from '../contact';
import {MdSnackBar} from '@angular/material';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { SidebarComponent } from '../sidebar/sidebar.component';
import {ContactService} from '../contact.service';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot,ActivatedRoute,Params } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import {Observable} from 'rxjs/Rx';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import { toString } from '@ng-bootstrap/ng-bootstrap/util/util';




@Component({
  selector: 'app-add-driver',
  templateUrl: './add-driver.component.html',
  styleUrls: ['./add-driver.component.css'],
  providers: [ContactService,SidebarComponent]
})
export class AddDriverComponent implements OnInit {
  text: any;
  timezoneArray(arg0: any): any {
    throw new Error("Method not implemented.");
  }



  contactNumber
  //File uploader above
  device_Id: string;
  dev: any;
  deviceId: any;
  group_info: any;
  executed2:any;
  groupInfo:any;
  devices: Device[] = []
  device: Device
  fuel_tank_capicity:any;
  voltage_tank_empty:any;
  tankfull_capicity:any;
  tokens: Token[] = []
  token: Token

   useridd: any;
   routeData : any=[];
   data:any;
  fs: any;
  ls: any;
  or: any;
  mb: any;
  custtype: any;
  cust: boolean;
  logoutbut: boolean;
  dealer: boolean;
  logo: any;
  superAdmin: any;
  myaccount(){
 
    this.cond = false
    this.router.navigateByUrl("accountSettings");
  // let dialogRef = this.dialog.open(MyaccountComponent, {
  //   width: '903px',
  //   data: {}
  // });

  // dialogRef.afterClosed().subscribe(result => {

  //   if(result == "succ"){
  //     console.log("Updated")
  //   }

  // });
  }
  group(){
    this.cond = false
    this.router.navigateByUrl("group_view");
  }
  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);
    
  }

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


  // new_1(){
  //   this.router.navigateByUrl("new");
    
  // }
  
 
  
  
  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 ++;
   }
  
    
  }
 
  Ddetail(){
    this.router.navigateByUrl("driverdetail");
  }
  DModel(){
    this.router.navigateByUrl("deviceModel");
  }
  VType(){
    this.router.navigateByUrl("VehicleType");
  }
  routeViolation(){
    this.cond = false
    this.router.navigateByUrl("device-report/routeViolation");
  
  }

  
  
  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");
  
  }
  ignition_report(){
    this.cond = false
    this.router.navigateByUrl("device-report/ignition_report");
  
  
  }
  
  geofancingReport(){
    this.cond = false
    this.router.navigateByUrl("device-report/geofancing");
  }

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

  }
  
  
  distance_report(){
  this.cond = false
  this.router.navigateByUrl("device-report/distance_report");
  }
  
  trip_report(){
    this.cond = false
    this.router.navigateByUrl("device-report/trip_report");
  
  }
  
  addgeo(){
    this.router.navigateByUrl("geofence-add");
  }
  geo(){
    this.router.navigateByUrl("geofencing");
    
  }

   a(){
    // 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 ++;
   }
  
    
  }
  addcus(){
    this.router.navigateByUrl("add");
  } report(){
    this.cond = false
    this.router.navigateByUrl("device-report");
  
  }
  report_speed(){
   // console.log("report speed call")
    this.cond = false
    this.router.navigateByUrl("device-report/device-speed-report");
  }
  name: any;
  address: any;
  status: any;
  license_number: any;
  license_upload: any;
  overall_rating: any;
  salary:any;
  doj: string;

  Manf: string;
  Model: string;
  tkstatus:any;
  value:any;
Lo:string;
  Hardware_Ver: string;
  Loca: string;
  temp:any
  food:any
  new:any;
  email:any;
  message:string;
  selectedValue:any;
  show:boolean =false;

  remove
  devicename: any;
  deviceid: any;
  des: any;
  model: any;
  Des: any;
  hrdwr: any;
  typdev:any;
  Device_ID: string;
  /* ../../assets/image/bgtry2.jpg */
 
  foodds = [
    {value: 'true', viewValue: 'True'},
    {value: 'false', viewValue: 'False'},
   
  ];
  cultivoChange(val){
  
    if(val.value == "Tracker"){
      this.show=true
    }
   else{
    this.show=false
   }
  }

  back2home(){
    // console.log("Runnig Back")
    this.router.navigateByUrl("dashboard");
    
  }
title="Add Driver";
buttonText="Add";
update:boolean=false
  constructor(public dialogRef: MdDialogRef<AddDriverComponent>,@Inject(MD_DIALOG_DATA) public data1: any ,private _formBuilder: FormBuilder,private router: Router, public snackBar: MdSnackBar,private contactService: ContactService,private _flashMessagesService: FlashMessagesService,private sidebar:SidebarComponent,public dialog: MdDialog,private act:ActivatedRoute) { 
   console.log(data1);
   
    if(Object.keys(data1).length != 0){
      this.update=true
      this.title="Edit Driver";
      this.buttonText="Update"
      this.name=data1.name;
      this.salary=data1.salary;
      this.doj=data1.date_of_joining;
      this.address=data1.address;
      this.status=data1.status;
      this.license_number=data1.license_number
      this.contactNumber=data1.contactNumber
    }else{
      this.update=false
      this.title="Add Driver";
      this.buttonText="Add"
    }
  }
test(){
//   console.log("Runnig Test")
//  console.log(this.new.value);
}

mydealer(){
  window.localStorage['token'] =  window.localStorage['Dealer_token'];
  localStorage.removeItem('devices');
  window.localStorage['DataUpdate'] = 'True';
  if(window.localStorage['DataLoaded'] = 'True'){
    window.localStorage['Custumer'] = 'OFF'
    this.router.navigateByUrl("add")
   // this.router.navigateByUrl("const?_status="+"OK");
  }
}
       /*  TOKEN GENERATION  */   

       

tokenn(){
  if(this.name == null)
  {
    
    this._flashMessagesService.show('Error : Insert the Complete Details', { cssClass: 'alert-danger', timeout: 1000 });
    this.tkstatus=0;
  }
  else{
    // console.log("GENERATING TOKEN")
 /*  const newToken ={
    deviceid: this.deviceid,
    eid: "test@test.com",
    }
     this.contactService.addToken(newToken)
      .subscribe(token => {
        this.tokens.push(token);
      });   
      this.tkstatus=1;  */
    }
    }

      /*  ADD DEVICE   */
     
      mess:any;
      mess2:any;
      mess3:any;
      neww:any;
      driver:any;
      before:any;
      dcontact:any;
      timer:any;
      subscription:any;
      Load:boolean=false
      ign(){
        this.router.navigateByUrl("device-report/ign-report");
      
      }
      addDriver(ngForm){
   
       // alert(this.useridd);
  if(this.name == null||this.address == null||this.status == null||this.license_number == null||this.salary == null||this.doj == null)
  {
    
    this._flashMessagesService.show('Error : Please insert details of Driver', { cssClass: 'alert-danger', timeout: 2000 });
    this.Load = false
  }
  // else if(this.address == null)
  // {
  //   this._flashMessagesService.show('Error : Insert the Address ', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }
  // else if(this.status == null)
  // {
  //   this._flashMessagesService.show('Error : Insert the Status', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

// second row
  // else if(this.license_number == null)
  // {
  //   this._flashMessagesService.show('Error : Insert license number', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

  // else if(this.license_upload == null)
  // {
  //   this._flashMessagesService.show('Error : Insert license upload', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

  // else if(this.overall_rating == null)
  // {
  //   this._flashMessagesService.show('Error : Insert overall rating', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

  // third row
  // else if(this.salary == null)
  // {
  //   this._flashMessagesService.show('Error : Insert salary', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }
  // else if(this.doj == null)
  // {
  //   this._flashMessagesService.show('Error : Insert date of joining', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

// else if(this.imagePath == null)
// {
//   this._flashMessagesService.show('Error : Insert image path', { cssClass: 'alert-danger', timeout: 2000 });
//   this.Load = false
// }



else{
  this._flashMessagesService.show('Driver Added', { cssClass: 'alert-danger', timeout: 1000 });
     }

 

    //this._flashMessagesService.show('Congratulation Device Added as '+this.deviceid, { cssClass: 'alert-success', timeout: 2000 });
    
    //object should form as per the request;

    if(this.update){
      this.updateDriver()
    }else{
      const newDriver ={
        name: this.name,
        address: this.address,
        status: this.status,
        license_number: this.license_number,
        overall_rating:this.overall_rating,
        salary:this.salary,
        doj:this.doj,
        userid :this.routeData,
        contactNumber:this.contactNumber,
  
      }
     //webservice to add new driver
  
        this.contactService.addDriver(newDriver)
        .subscribe((dataret => {
          this.data = dataret
          this.NewVehicleType(ngForm);
          if(this.data.status == 200){
          
            //this.driver.push(newDriver);
            this._flashMessagesService.show("New Driver Added!", { cssClass: 'alert-danger', timeout: 2000 });   
            
          } 
         
           }), (err: any) => { 
          //    console.log(err.status); 
          // console.log(err);
       if(err.status ==   500)
        {
          
    
           this.mess = err._body.split(":")[5] ;
           this.mess2 = this.mess.split("_")[0];
          this.mess3 = this.mess.split("_")[1];
       
       //   this._flashMessagesService.show(this.mess2 + this.mess3+" Duplicate Entry", { cssClass: 'alert-danger', timeout: 3000 });
          this.Load = false
          // console.log("Error"); 
          }  
         else{
          this._flashMessagesService.show("Error !!", { cssClass: 'alert-danger', timeout: 2000 });        
          this.Load = false
        } 
        }
      );
      
    }
     
  }

  updateDriver(){
    var data={
      _id:this.data1._id,
       name: this.name,
      address: this.address,
      status: this.status,
      license_number: this.license_number,
      overall_rating:this.overall_rating,
      salary:this.salary,
      doj:this.doj,
      contactNumber:this.contactNumber,
      userid :this.data1.user_id._id
    }

    this.contactService.post('/driver/updateDriverDetails',data).subscribe(res=>{
      // this.dialogRef.close();
    })
  }


  // imageFile:any;
  // Filename:any;
  // Lfilename:any;
  private fileCounter = 0;
// -------------------profile upload----------------------------------
//   onBeforeUpload = (metadata) => {
//     if (this.fileCounter % 2 === 0) {
//       metadata.abort = true;
//     } else {
//       // mutate the file or replace it entirely - metadata.file
//       metadata.url = 'http://13.126.36.205:3000/vehicleType/profileUpload'
//     }
  
//     this.fileCounter++;
//     return metadata;
//   };
//   onUploadFinished(file) {
//     debugger;
//     console.log(file);
//     this.imageFile=file;
//     console.log(this.imageFile.file.name);
//     this.Filename=this.imageFile.file.name
//   }
  
//   onRemoved(file) {
//     console.log(file);
//   }
  
//   onUploadStateChanged(state: boolean) {
//     console.log(state);
//   }

// //---------------license upload------------------
// onBeforeUpload1 = (metadata) => {
//   if (this.fileCounter % 2 === 0) {
//     metadata.abort = true;
//   } else {
//     // mutate the file or replace it entirely - metadata.file
//     metadata.url = 'http://13.126.36.205:3000/vehicleType/licenseUpload'
//   }

//   this.fileCounter++;
//   return metadata;
// };
// onUploadFinished1(file) {
//   debugger;
//   console.log(file);
//   this.imageFile=file;
//   console.log(this.imageFile.file.name);
//   this.Lfilename=this.imageFile.file.name
// }

// onRemoved1(file) {
//   console.log(file);
// }

// onUploadStateChanged1(state: boolean) {
//   console.log(state);
// }

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

}
NewVehicleType(ngForm){
  //this.router.navigateByUrl("addEditVehicleType"); 
  this.driver=[];
  ngForm.reset();
}
click1(event){
  if((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39){
    
          }
          else
            event.preventDefault();
        }

  ngOnInit() {
    
  
  //  console.log(moment("2014-06-01T12:00:00Z").tz('America/Los_Angeles').format('ha z'));
    this.logo=window.localStorage['logo'];
   
    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.email = 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;
    if(this.custtype == true){
      this.cust = true;
    }  
         

         if(this.mb.charAt(0)=="n"){
          this.mb = ' '
        }
    if(this.mb.charAt(0)=="n"){
      this.mb = ' '
    }
    if( window.localStorage['Custumer'] == 'ON'){
      this.logoutbut = false
      this.dealer = true
   }
   else{
       this.logoutbut = true
   }
 
   this.logo=window.localStorage['logo'];
   this.text=window.localStorage['text'];

    this.act.queryParams.subscribe((params:Params) =>{ 


      // console.log(params['useridd']);
      this.routeData=params.user_id;
      // let id= params['user_id'];
      // this.groupId = id;
      // console.log(this.groupId);
    
    
      })
   


  }
   
    }
//     call(e) {
//       {
//              if (e.keyCode == 32) {
//                  e.preventDefault();
//              }
//          }
//  }
//     click1(event){
     
//       if((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39){
//       }
//       /* if(event.keyCode===13){
//       this.otp_window();
//       } */
      
//       else
//       event.preventDefault();
//       } 
//  fs:any;
//  ls:any;
//  or:any;
//  userid:any;
//    emailid :any; 
//    useridd:any;
//    custtype:any;
//    cust:boolean=true;
//    isLinear = false;
//    firstFormGroup: FormGroup;
//    secondFormGroup: FormGroup;
//    phoneno: any;
//    logo:any;
//    text:any;
//    ideal(){
//     this.router.navigateByUrl("device-report/ideal-report");
//   }
//   mb:any
  // logoutbut:boolean;
// dealer:boolean;
// groups=[];
  

  // group(){
  //   this.cond = false
  //   this.router.navigateByUrl("group_view");
  // }


  // fuel_calibration(){
  //   console.log("Inside fuel Callibration !!!");
  //   if(this.fuel_tank_capicity == null)
  //   {
      
  //     this._flashMessagesService.show('Error : Empty entry', { cssClass: 'alert-danger', timeout: 2000 });
  //     this.Load = false
  //   }
  //   else if(this.voltage_tank_empty == null)
  //   {
  //     this._flashMessagesService.show('Error : Empty entry', { cssClass: 'alert-danger', timeout: 2000 });
  //     this.Load = false
  //   }
  //   else if(this.tankfull_capicity == null)
  //   {
  //     this._flashMessagesService.show('Error : Empty entry', { cssClass: 'alert-danger', timeout: 2000 });
  //     this.Load = false
  //   }


  //   const fuelCapicity ={
  //     fuelCapicity: this.fuel_tank_capicity,
  //     voltageTankempity: this.voltage_tank_empty,
  //     tankfullcapicity: this.tankfull_capicity,
      
  //   }

  //   console.log(fuelCapicity);
  // }
  //}


  


