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

import {Driver} from '../driver';
import {Token} from '../token';
import {Vehicle} from '../vehicle';
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-edit-vehicle-type',
  templateUrl: './add-edit-vehicle-type.component.html',
  styleUrls: ['./add-edit-vehicle-type.component.css'],
  providers: [ContactService,SidebarComponent]
})
export class AddEditVehicleTypeComponent implements OnInit {
  [x: string]: any;

  
  device_Id: string;
  dev: any;
  deviceId: any;
  group_info: any;
  executed2:any;
  groupInfo:any;


  devices: Device[] = [];
  device: Device;

  vehicle_types:Vehicle[]=[];
  vehicle_type:Vehicle;
   IconType = [
    { value: 'car', viewValue: 'Car' },
    { value: 'bike', viewValue: 'Bike' },
    { value: 'bus', viewValue: 'Bus' },
    { value: 'pickup', viewValue: 'Pickup' },
    { value: 'tractor', viewValue: 'Tractor' },
    { value: 'truck', viewValue: 'Truck' },
    { value: 'truck', viewValue: 'Heavy Truck' },
    { value: 'tanker', viewValue: 'Tanker' },
    { value: 'jcb', viewValue: 'JCB' },
    { value: 'roadroller', viewValue: 'Roadroller' },
    { value : 'user' ,viewValue : 'User'},
    { value : 'ambulance' ,viewValue : 'Ambulance'},
    // { value : 'tempo' ,viewValue : 'Tempo'}
   
  ];
  // { value : 'user' ,viewValue : 'User'}
  // Bike Bus Car Heavy truck Pickup Tanker Tractor Truck JCB Roadroller
  iconObj:any;
  fuel_tank_capicity:any;
  voltage_tank_empty:any;
  tankfull_capicity:any;
  tokens: Token[] = []
  token: Token

   useridd: any;
   routeData : any=[];
   data:any;
  custtype: any;
  cust: boolean;
  mb: any;
  dealer: boolean;
  logoutbut: boolean;
  fs: any;
  ls: any;
  or: any;
  logo: any;
  superAdmin: any;

   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();
          }
  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")
  //   }

  // });
  }
  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");
  // }
  brand: any;
  description: any;
  model: any;

 // voltage_calibration=[{voltage:[],fuel:[]}];
  voltage_calibration=[];
  temprature_calibration=[];
  volts;
  ltrs:any=[];
  
  tank_size: number;
  mileage: number;
  
  
  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;

 
  /* ../../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");
    
  }

  constructor(private _formBuilder: FormBuilder,private router: Router, public snackBar: MdSnackBar,private contactService: ContactService,private _flashMessagesService: FlashMessagesService,private sidebar:SidebarComponent,public dialog: MdDialog,private act:ActivatedRoute) { }
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  */   

       


      /*  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");
      
      // }
      addVehicleType(signupForm){
        // console.log("vehicle ICon",this.iconObj);
  
  if(this.brand == null ||this.description == null|| this.model == null ||this.voltage_calibration  == null||this.tank_size == null||this.mileage == null)
  {
    
    this._flashMessagesService.show('Error :Please Insert Details', { cssClass: 'alert-danger', timeout: 5000 });
   // this.Load = false
   //this.router.navigateByUrl("addEditVehicleType");
   return;
  }
  // else if(this.description == null)
  // {
  //   this._flashMessagesService.show('Error : Please Insert Description ', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }
  // else if(this.model == null)
  // {
  //   this._flashMessagesService.show('Error : Please Insert Model', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

// second row
  // else if(this.voltage_calibration  == null)
  // {
  //   this._flashMessagesService.show('Error : Please insert Voltage', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

  // else if(this.tank_size == null)
  // {
  //   this._flashMessagesService.show('Error : Please Insert Tank Size', { cssClass: 'alert-danger', timeout: 2000 });
  //   this.Load = false
  // }

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




else{
  const newVehicleModel ={
    brand: this.brand,
    description: this.description,
    model: this.model,
    voltage_calibration: this.voltage_calibration,
    temp_calibration: this.temprature_calibration,
    tank_size: this.tank_size,
    mileage: this.mileage,
    iconType:this.iconObj.value,
    user:this.useridd
  }

  console.log('newVehicleModel',newVehicleModel);
//webservice to add new driver  
   // console.log('finalPayload',newVehicleModel)
   this.contactService.addVehicleType(newVehicleModel)
   .subscribe((dataret => {
     // this.data = dataret
     // this.NewVehicleType(signupForm);
    //  this._flashMessagesService.show('Vehicle Type Added', { cssClass: 'alert-success', timeout: 2000 });
     this.router.navigateByUrl("VehicleType");
     // this.router.navigateByUrl("VehicleType");
      }), (err: any) => {
   
  if(err.status ==   500)
   {
     

      this.mess = err._body.split(":")[5] ;
      this.mess2 = this.mess.split("_")[0];
     this.mess3 = this.mess.split("_")[1];
  

     this.Load = false
  
     }  
    else{
     this._flashMessagesService.show("Error !!", { cssClass: 'alert-danger', timeout: 2000 });        
     this.Load = false
   } 
   }
 );

   
     }

 

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

  NewVehicleType(ngForm){
    //this.router.navigateByUrl("addEditVehicleType"); 
    this.router.navigateByUrl("VehicleType");
    // this.vehicle_types=[];
    // ngForm.reset();
  }


  imageFile:any;
  Filename:any;
  private fileCounter = 0;

  
  group(){
    this.cond = false
    this.router.navigateByUrl("group_view");
  }
  onRemoved(file) {
    // console.log(file);
  }
  report_map(){
    this.router.navigateByUrl("routeMapping");
  
  }
 
  // loadRow(){
  //   this.voltage_calibration.push({voltage:0,fuel:0});
  // }


  addRow(voltage,fuel){
    var obj={};
    //let contact =  this.voltage_calibration({voltage:0,fuel:0});
    obj={voltage:voltage,fuel:fuel};
    this.voltage_calibration.push(JSON.parse(JSON.stringify(obj)));
    obj={};
  }

  addTempRow(voltage,temp){
    var obj={};
    //let contact =  this.voltage_calibration({voltage:0,fuel:0});
    obj={voltage:voltage,temp:temp};
    this.temprature_calibration.push(JSON.parse(JSON.stringify(obj)));
    obj={};
  }
  deltempRow(index){
    this.temprature_calibration.splice(index, 1);
  }

  deleteRow(index){
    this.voltage_calibration.splice(index, 1);
  }
  ngOnInit() {
    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);
      this.addRow(0,0);
      this.addTempRow(0,0);
    
      })
   


  }
}
