import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { ContactService } from '../../contact.service';
import { Params, Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { MyaccountComponent } from '../../myaccount/myaccount.component';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-device-speed-report',
  templateUrl: './device-speed-report.component.html',
  styleUrls: ['./device-speed-report.component.scss'],
  providers: [ContactService]

})
export class DeviceSpeedReportComponent implements OnInit {
  date1: Date = new Date();

  option: any;

  neww: any;
  Load: Boolean = false
  creategraph() {

    // console.log('deviceObj=>',this.dataSelect[0].did);

    let r = new Date(this.date1).toISOString();
    // console.log(r);
    this.Load = true;
    this.contactService.getSpeedreport(this.dataSelect[0].did, r).subscribe(

      data => {
        this.Load = false;
        this.device_data = data
        //console.log(this.device_data); 
        this.lineChartLabels.length = this.device_data.length;
        this.getdata(this.device_data)

      });

  }

  before: any;

  // logout() {
  //   window.localStorage.clear();
  //   this.router.navigateByUrl("login");
  // }
  // devi() {
  //   this.router.navigateByUrl("dashboard");

  // }
  // soon() {
  //   this.router.navigateByUrl("const?_i=" + window.localStorage.token);

  // }

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

  // addcus() {
  //   this.router.navigateByUrl("add");
  // }
  // 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");

  // }
  // ign() {
  //   this.router.navigateByUrl("device-report/ign-report");

  // }

  // vehicleRoute() {
  //   this.router.navigateByUrl("vehicleRoute");

  // }

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

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

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

  // }

  // distance_report() {

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


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

  // }

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

  // }


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


  new() {
    this.router.navigateByUrl("new");

  }
  cond: Boolean = false;
  point: any = 0;
  // 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++;
  //   }


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

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


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

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


  // }





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

  // }

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

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

  // report_speed() {
  //   // console.log("report speed call")
  //   this.cond = false
  //   this.router.navigateByUrl("device-report/device-speed-report");
  // }
  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");
    }
  }
  _lineChartData: any;
  public info: string;
  public prevDatasets;

  options = [];

  // ideal() {
  //   this.router.navigateByUrl("device-report/ideal-report");
  // }

  getdata(final) {
    let fi = [];
    let time = [];
    this.lineChartLabels.length = 0;
    for (let q = final.length - 1; q > 0; q--) {
      fi.push(final[q].speed);
      let t = new Date(final[q].time).toLocaleTimeString();
      // console.log(t);
      //let k = JSON.stringify(final[q].time).split("T")[1].split(".")[0];
      this.lineChartLabels.push(t)
    }
    this.Load = false;
    this.lineChartData = [{
      label: "Speed",
      data: fi
    }];

  }




  // lineChart
  public lineChartData: Array<any> = [
    { data: [0, 0, 0, 0, 0, 0, 0], label: 'Speed' },
  ];

  public lineChartLabels: Array<any> = ['', '', '', '', '', '', ''];
  public lineChartOptions: any = {
    responsive: true,
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: false,
          max: 6000,
          min: 0
        }
      }]
    }

  };
  public lineChartColors: Array<any> = [
    { // grey
      backgroundColor: 'rgba(148,159,177,0.2)',
      borderColor: 'rgba(148,159,177,1)',
      pointBackgroundColor: 'rgba(148,159,177,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(148,159,177,0.8)'
    },
    { // dark grey
      backgroundColor: 'rgba(77,83,96,0.2)',
      borderColor: 'rgba(77,83,96,1)',
      pointBackgroundColor: 'rgba(77,83,96,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(77,83,96,1)'
    },
    { // grey
      backgroundColor: 'rgba(148,159,177,0.2)',
      borderColor: 'rgba(148,159,177,1)',
      pointBackgroundColor: 'rgba(148,159,177,1)',
      pointBorderColor: '#fff',
      pointHoverBackgroundColor: '#fff',
      pointHoverBorderColor: 'rgba(148,159,177,0.8)'
    }
  ];
  public lineChartLegend: boolean = true;
  public lineChartType: string = 'line';



  // events
  public chartClicked(e: any): void {
    // console.log(e);
  }

  public chartHovered(e: any): void {
    // console.log(e);
  }
  // myaccount() {

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

  constructor(private contactService: ContactService, private router: Router, public dialog: MdDialog) { }
  fs: any;
  ls: any;
  emailid: any;
  or: any;
  useridd: any;
  time: any;

  device_data: any;
  devicess: any;
  final: any;
  custtype: any;
  cust: boolean = false;
  logoutbut: boolean;
  dealer: boolean;
  logo: any;
  text: any;
  devicesss: any;
  finall: any;
  mb: any;
  superAdmin: Boolean = false;
  ngOnInit() {

    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;

    // this.getdev();


    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.logo = window.localStorage['logo'];
    this.text = window.localStorage['text'];
    this.time = new Date();

    this.contactService.getDevice(this.emailid, this.useridd).subscribe(

      data => {
        this.devicesss = data
        /*  this.final = this.devicess.devices[0]; */
        this.finall = (this.devicesss.devices);

        for (let i = 0; i < this.devicesss.devices.length; i++) {

          // if (this.devicesss.devices[i].type_of_device == "Tracker") {
            /*      let a ={
                   dname : this.devicess.devices[i].Device_Name,
                   did:this.devicess.devices[i].Device_ID,
                   id:this.devicess.devices[i]._id,
                   user:this.devicess.devices[i].user
                 }
                 this.options.push(a); */
            let a = {
              value: this.devicesss.devices[i].Device_Name,
              viewValue: this.devicesss.devices[i].Device_Name,
              did: this.devicesss.devices[i].Device_ID,
              id: this.devicesss.devices[i]._id,
              user: this.devicesss.devices[i].user,
              // email: this.devicesss.devices[i].Email_ID,
              // deviceType: this.devicesss.devices[i].type_of_device
            }
            this.options.push(a);

          }

        // }



      });

    /* 
        this.contactService.getSpeedreport("087074133830").subscribe(
          
          data => {
            this.Load = false;
            this.device_data = data 
           console.log(this.device_data); 
           this.lineChartLabels.length = this.device_data.length;  
           this.getdata(this.device_data)
      
          }); */


  }
  dataSelect = [];
  filterStates(val) {

    // console.log(val)
    // console.log(this.options)

    if (val) {
      const filterValue: any = val
      this.dataSelect = this.options.filter(function (d) {

        return d.value.toLocaleLowerCase().indexOf(filterValue.toLocaleLowerCase()) > -1;
      });
      return this.dataSelect;
    }

  }



}
