import { Component, OnInit } from '@angular/core';
import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material';
import {DialogContentExampleDialogComponent} from '../dialog-content-example-dialog/dialog-content-example-dialog.component'
/* import {Tab} from './tab'; */
import {Device} from '../device';

import {Driver} from '../driver';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';
/* import { DeviceReportComponent } from '../device-report/device-report.component';
 */import { DeviceEditComponent } from '../dashboard/device-edit/device-edit.component';
import {MdSnackBar} from '@angular/material';
import { DeviceShareComponent } from '../dashboard/device-share/device-share.component';
import { ShareUserComponent } from '../dashboard/share-user/share-user.component';
import { Params,Router, ActivatedRoute, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {ContactService} from '../contact.service';
import { checkNoChangesNode } from '@angular/core/src/view/view';
import { SpeednotifyComponent } from '../dashboard/speednotify/speednotify.component';
import { SidebarComponent } from '../sidebar/sidebar.component';
import { MyaccountComponent } from '../myaccount/myaccount.component';
import { AddDriverComponent } from '../add-driver/add-driver.component';

declare var $: any;
declare var moment:any;
declare var swal:any;

declare var google: any;

@Component({
  selector: 'app-driver-detail',
  templateUrl: './driver-detail.component.html',
  styleUrls: ['./driver-detail.component.css'],
  providers: [ContactService,SidebarComponent]

})
export class DriverDetailComponent implements OnInit {
  adbtn: string;
  chkAddBtn: string;
 //private url = 'http://localhost:3000/api/graph';  
  private socket;
  Load:boolean=false
 messages = [];
 connection;
 graphs:any;
 message;
  numberOfOnlineUsers: number;
devices: Device[];
device: Device;

drivers:any=[];
driver:any=[];
Device_ID: string;
Serial_Num: string;
Manf: string;
Model: string;
del:boolean = false;
Des: string;
Hardware_Ver: string;
Loca: string;
login:any;  
visibility:any;
/* tabs: Tab[] = []; */
calculateResult=[];
value:any;
a:any;
homeVis:any;
visibility0:any;
j:any;
id:any;
dev:any;
checked:any
MdSlideToggleChange :any;
e: Event;
d:any;
  tabelObj: any;



// deleteRecord(data){
//   this.contactService.deleteDriver(data).subscribe(  
//     data => {  
//       this.drivers=[];
//       this.driver=[];
//       this.getDriver();

//     });
// }



cond:Boolean = false;
point : any = 0;




add_Driver(){

this.router.navigate(["addDriver"],{queryParams :  {user_id : this.useridd}});

}



  constructor(public sidebar :SidebarComponent,public dialog: MdDialog,public snackBar: MdSnackBar,private router: Router, private contactService: ContactService, private activatedRoute: ActivatedRoute) { 
   
  }

sha :any;




myInput:any;
data_descip :any;
before:any;
// TOAST

fs :any;
ls :any;
or :any;
/* e =[];
 */token :any;
emailid :any;
devicess :any;
devicesss :any;
userID:any;
final:any;
lat:any;
lng:any;
latLongArr:any
convertedToString :String;
useridd:any;
notifi = [];
g:any;

custtype:any;
cust:boolean=false;

mb:any;
logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
data_to_view=[];
Durations:any;
superAdmin:Boolean = false;

  ngOnInit() {


    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.adbtn = localStorage.getItem("dlrchk")
   
   this.logo=window.localStorage['logo'];
   this.text=window.localStorage['text'];  
    window.localStorage['DataUpdate'] = 'True'
    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.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;

    this.custtype =  JSON.parse(window.atob(window.localStorage.token.split('.')[1])).isDealer;
    // console.log("abc", this.custtype);
    //this.getdev();
    if(this.custtype == true){
      this.cust = true;
    }  
         let  foods = [ ];

         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.testTable();

  }

  getDriver(){
    this.contactService.getDriver(this.useridd).subscribe(
          
      data => {
     
       for(let i=0;i<data.length;i++){
        this.driver.push(data[i]);
        //  console.log( this.driver);
      
        }
  
      });
      
  }

/*   this.socket = io.connect('https://13.126.36.205:5000');
  this.socket.on('connect', function(){
    console.log("IO Connected");
  
  }); */
  deviceData=[];
  arrival_time:any;
  baba=[]
  status_toShow:any;
  address_show:any;
  lattitude:any;
  longitude:any;
  
  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function() {
       that.tabelObj = $('#deviceTable').DataTable({
            'serverSide': false,
            "processing": true,
            "searching": true,
            pagingType: 'full_numbers',
            pageLength: 25,
            "scrollY":'65vh',
            // "ordering": true,
            order: [[0, 'desc']],  
            "scrollCollapse": true,     
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            ajax: (dataTablesParameters,callback) => {
              dataTablesParameters.op = {};
              dataTablesParameters.select = [];
              dataTablesParameters.find = {};

              var suburl = "";
              suburl += "/driver/getDrivers?userid="+that.useridd;
              that.contactService.get(suburl).subscribe(resp => {
                  console.log("Response from datatable=>", resp); 
            
                  callback({data : resp });
              }, err => {
                callback({data : [] });
              });
            
          },  
          "rowCallback": function(row: Node, data: any | Object, index: number){
            $('#deleteDriver',row).bind('click',()=>{  
              swal({
                  // title: 'Are you sure?',
                  text: "Do you want to delete driver data?",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, delete'
                }).then((result: { value: boolean; }) =>{                      
                  if(result){
                    console.log(data._id);
                    that.contactService.deleteDriver(data._id).subscribe(  
                      data => {  
                         
                        swal(
                          'Deleted',
                          'Driver deleted',
                          'success'
                        )

                        that.tabelObj.ajax.reload();
                  
                      });
              
                  }                
                });
          })

          $('#editDriver',row).bind('click',()=>{  
             const dialog= that.dialog.open(AddDriverComponent, {
              width: '800px',
              // height: '700px',
              data: data
          });

          dialog.afterClosed().subscribe(result => {
            that.tabelObj.ajax.reload();
            // //console.log(result);

          })
      })

            },
        
            "columns": [
              {
                "data": "_id",
                "visible":false,
                "defaultContent": "",
                "render": function(data, type, row) {  
                  return data?data : '';                  
                }
            },
            {
              "data": "name",
              "defaultContent": "",
              "render": function(data, type, row) {  
                return data?data : '';                  
              }
          },
          
              {
                "data": "address",
                "defaultContent": "",
                "render": function(data, type, row) {  
                  return data?data : '';                  
                }
            },
                {
                    "data": "status",
                    "defaultContent": "",
                    "render": function(data, type, row) {  
                      return data?data : '';                  
                    }
                },
                {
                    "data": "license_number",
                    "defaultContent": "",
                    render: function(data, type, row) {
                     return data?data:''; 
                    }
                }, 
                {
                  "data": "salary",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data?data:'';        
                  }
              }, 
                {
                  "data": "date_of_joining",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    var doj = new Date(data);
                    return data ? (moment(doj).format('llll')) : "";  
                  }
              }, 
         
            {                
              "data":null,
            
              "render":function(data,type,row){  
                  return '<i id="deleteDriver" class="fas fa-trash" style="cursor:pointer;color:green" title="Delete driver"></i>'
              }
          },
          {                
              "data":null,
            
              "render":function(data,type,row){  
                  return '<i id="editDriver" class="fas fa-edit" style="cursor:pointer;color:green" title="Delete driver"></i>'
              }
          }  

            ],  

        });
  
    });
  
  }
  tab:any;

  exportToExcel(){
    console.log("IN EXPORT")
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
	    var textRange; var j=0;
      var table = $('#deviceTable').clone();
    
      table[0].querySelector("thead").remove();
      table[0].prepend($(".dataTable thead").clone()[0]);
    this.tab = table[0];
  
	    for(j = 0 ; j < this.tab.rows.length ; j++) 
	    {     
	        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
	     
	    }

	    tab_text=tab_text+"</table>";
	 
	    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); 

	    var ua = window.navigator.userAgent;
	    var msie = ua.indexOf("MSIE "); 

	    var sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

	    return (sa);
  }
  

}
