import { Component, 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-device-model',
  templateUrl: './add-device-model.component.html',
  styleUrls: ['./add-device-model.component.css'],
  providers: [ContactService,SidebarComponent]
})
export class AddDeviceModelComponent implements OnInit {
  sos_number:any;
  chk_status:any;
  stop_engine:any;
  restore_engine:any;
 
  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;
  mb: any;
  logoutbut: boolean;
  dealer: boolean;
  custtype: boolean;
  cust: boolean;
  fs: any;
  ls: any;
  or: any;
  logo: any;
  superAdmin: any;
  timeZone:any;
  apn:any;
  sms_ip;
  sms_apn;
  sms_timezone;
  text: any;
  Manufacturer: any;
  immValue: any;
  immobilizerCmd: any;
  deviceport : 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")
  //   }

  // });
  }
  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");
  }
  
  NewVehicleType(){
    this.router.navigateByUrl("deviceModel"); 
    // this.devices=[];
    // ngForm.reset();
  }


  // new_1(){
  //   this.router.navigateByUrl("new");
    
  // }
  
  notification(){
    this.cond = false
    this.router.navigateByUrl("notifications");
  }
  
  
  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");
  }
  device_type: any;
  config_cmd: any;
  loc_cmd: any;
  imob_cmd: any;
  reset_cmd: any;
  resume_cmd: any;
  
  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");
      
      }
      addDeviceModel(signupForm){
     
        // alert(this.useridd);
  if(this.device_type == null||this.config_cmd == null||this.loc_cmd == null||this.imob_cmd == null||this.reset_cmd == null||this.resume_cmd == null)
  {  
    this._flashMessagesService.show('Error :Please Insert details of Device type', { cssClass: 'alert-danger', timeout: 2000 });
    this.Load = false;
    return;
  }

    const newDeviceModel ={
      device_type: this.device_type,
      config_cmd: this.config_cmd,
      loc_cmd: this.loc_cmd,
      imob_cmd: this.imob_cmd,
      reset_cmd: this.reset_cmd,
      resume_cmd:this.resume_cmd,
      // sms_ip:this.sms_ip,
      // sms_apn:this.sms_apn,
      // sms_timezone:this.sms_timezone
      
    }

    if(this.sms_ip){
      newDeviceModel['sms_ip'] = this.sms_ip;
    }

    if(this.sms_apn){
      newDeviceModel['sms_apn'] = this.sms_apn;
    }

    if(this.sms_timezone){
      newDeviceModel['sms_timezone'] = this.sms_timezone;
    }

   //webservice to add new driver
   if(this.timeZone){
    newDeviceModel['device_timezone'] = this.timeZone;
   }
   if(this.apn){
    newDeviceModel['device_apn'] = this.apn;
   }
    if(this.Manufacturer){
      newDeviceModel['Manufacturer'] = this.Manufacturer;
    }

    if(this.deviceport){
      newDeviceModel['deviceport'] = this.deviceport;
    }

    if(this.immobilizerCmd){
      newDeviceModel['imobliser_type'] = this.immobilizerCmd;
    }
    console.log(newDeviceModel);
    
      this.contactService.addDeviceModel(newDeviceModel)
      .subscribe((dataret => {
        this.data = dataret;
        // this._flashMessagesService.show('Device Model Added', { cssClass: 'alert-success', timeout: 2000 });
        // this.NewVehicleType(signupForm);
        this.router.navigateByUrl('deviceModel');
         }), (err: any) => { 
          this._flashMessagesService.show('Internal Server Error', { cssClass: 'alert-denger', timeout: 2000 });
      }
    );
     
  }


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

 
  
  onRemoved(file) {
    // console.log(file);
  }
  group(){
    this.cond = false
    this.router.navigateByUrl("group_view");
  }
  report_map(){
    this.router.navigateByUrl("routeMapping");
  
  }
  

  immobilizere=[
    {
      value : 'serverCmmand',
      Viewvalue : 'Server command'
      
    },
    {
      value : 'mobCmd',
      Viewvalue : 'Mobile command'
      
    }
  ]
  ngOnInit() {
    this.immobilizere;
    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.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.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'];
  

  }
 
  immobilizerType(ev:any){
    if(ev == "serverCmd") this.immobilizerCmd = '1.0';
    if(ev == "mobileCmd") this.immobilizerCmd = '0.0';
    console.log(this.immobilizerCmd);
  }
}
