import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router'
import { ContactService } from '../contact.service';
import { RouteDeleteComponent } from '../route-delete/route-delete.component';
import { MdDialog } from '@angular/material';
import { TrackedVehiclesComponent } from './tracked-vehicles/tracked-vehicles.component';
declare var $:any;
declare var moment : any ;
declare var swal:any;
@Component({
  selector: 'app-vehicle-route',
  templateUrl: './vehicle-route.component.html',
  styleUrls: ['./vehicle-route.component.scss']
})
export class VehicleRouteComponent implements OnInit {
  identifier:any='routeList';
  before:any;
  logoutbut:boolean;
  cust:boolean=false;
  logo:any;
  text:any;
  fs:any;ls:any;emailid:any;or:any;useridd:any;mb:any;custtype:any;dealer:any;
  showImage:any;
  groups=[];
  group_info:any;
  myInput:any;
  deviceId:any;
  device_update:any;
  superAdmin:Boolean = false;
  deviceStatus:any;
  statusValue = ["Active","InActive","Restricted"];
  routeStatus:any;
  state_1:any;
  tabelObj: any;
  constructor(private router: Router,private contactService: ContactService,public dialog: MdDialog) { }

  ngOnInit() {
   
   
    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.logo=window.localStorage['logo'];
    this.text=window.localStorage['text'];  
     window.localStorage['DataUpdate'] = 'Tthis.rue'
   
   
     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;
    //  console.log('testing',this.useridd);
     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.routeDetails(this.useridd);
    this.testTable()
  }

  exportExcel(){

  }
  getReport(event){
  
    console.log("inside function");
    if(event == 'getExcel'){
      this.exportExcel();
    }else{
      var deviceId: any;
      var tpdata = event ; 
    
       this.tabelObj.ajax.reload();  
      // this.tabelObj.draw();  
     
    }
   
  }

  
  
  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function() {
       that.tabelObj = $('#deviceTable').DataTable({
            "processing": true,
            "searching": true, 
            pagingType: 'full_numbers',
            pageLength: 25,
            serverSide: false,
            "scrollY":'65vh',  
            "scrollCollapse": true,     
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            ajax: (dataTablesParameters,callback) => {
       
               var suburl = "/trackRoute/user/" + that.useridd;
               if(that.findByStatus){
                 suburl += "?status=" + that.findByStatus;
               }
           
                that.contactService.get(suburl).subscribe(resp => {   
                  console.log('resp',resp);
                  callback({data : resp });
              }, err => {   
                 callback({data : [] });
                console.log("error",err) ;     
              });       
          },  
          "rowCallback": function (row: Node, data: any | Object, index: number) {
            $('#delete', row).bind('click', () => {
              // console.log("delete Method", data);
           
              swal({
                title: 'Are you sure?',
                text: "Seleted route will be deleted .",
                type: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Clear'
            }).then((result: { value: boolean; }) => {
                if (result) {
                  var rId = data._id;
                  that.contactService.delRouteDetail(rId)
                  .subscribe(res => {
                    swal(
                      'Deleted',
                      'Selected route has been deleted',
                      'success'
                  )
                    that.tabelObj.ajax.reload();  
                  })
  
                }
            });
         
          });
          $('#viewroute', row).bind('click', () => {
            that.vehiclePath(data)
        });
         $('#trackedVehicles', row).bind('click', () => {
            that.untrack(data)
        });
          },

            "columns": [
                {
                    "data": "name",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        
                      return data?data : '';                  
                    }
                },
                {
                    "data": "source",
                    "defaultContent": "",
                    render: function(data, type, row) {
                      return data?data:'';        
                    }
                },
                {
                    "data": "destination",
                    "defaultContent": "",
                    render: function(data, type, row) {
                      // var expDate = new Date(data);
                      return data ? data : "";  
                  
                    }
                }, 
          
                
              {
                "data": "status",
                "defaultContent": "",
                render: function(data, type, row) {        
                  return data ? data : "";  
                }
            }  ,
            {
              "data": "speed_alert",
              "defaultContent": "",
              render: function(data, type, row) {        
                return data ? data : "";  
              }
          }  ,
                 
            {
              "data": null,
              "defaultContent": "",
              render: function(data, type, row) {        
                // return '<button id="delete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete</button>'
                return  '<i id="delete" class="fas fa-trash-alt" style="cursor:pointer" title="Delete route"></i>'
              }
          }            
          ,
          {
              "data": null,
              "defaultContent": "",
              render: function(data, type, row) {        
                // return '<button id="delete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete</button>'
                return  '<i id="trackedVehicles" class="fas fa-car" style="cursor:pointer" title="Tracked vehicles"></i>'
              }
          },
          {
            "data": null,
            "defaultContent": "",
            render: function(data, type, row) {        
              // return '<button id="delete" type="button" class="btn btn-primary" style="background:red;border:0px;">Delete</button>'
            
              return '<i  id="viewroute" style="cursor:pointer" title="View route"  class="fas fa-eye"></i>'
            }
        }                       
            ],  
            // "columnDefs": [
            //   { className: "dt-body-left", "targets": [ 0,1,2,3 ] },
            //   {
            //     "targets": '_all',
            //     "createdCell": function (td, cellData, rowData, row, col) {
            //         $(td).css('padding', '18px')
            //     }
            // } ,
            // { "width": "10px", "targets": 0 },
            // { "width": "40px", "targets": 1 },
            // { "width": "100px", "targets": 2 },
            // { "width": "70px", "targets": 3 },
         
            // ] 
        });
  
    });
  
  }
  

// route_detail_show:any;
// routeDetails(uId){
 
//   this.route_detail_show=[];
 
//   // console.log(uId);
//   this.contactService.getRouteDetail(uId)
//     .subscribe(res=>{
//       this.route_detail_show=res;
//     })

  
// }




vehiclePath(routePath){

  localStorage.setItem('routeData', JSON.stringify(routePath))
  localStorage.setItem('routeId', routePath._id);
 // this.cond = false
//  console.log(routePath._id);
 localStorage.setItem('routeId',routePath._id)
  this.router.navigateByUrl('viewRoute');
}



// deleteRoute(rId){
 

//   let dialogRef = this.dialog.open(RouteDeleteComponent, {
//     height:'300px',
//     width:'430px',
//     data: {rId}
//   });
//       dialogRef.afterClosed().subscribe(result => {  
   
//         if(result=="success"){
          
//           this.contactService.delRouteDetail(rId)
//           .subscribe(res => {
         
        
//             this.routeDetails(this.useridd);
//           })
              
           
//         }else if(result=="Cancel"){
        
//         }
//       });
// }

state:any;

updateStatus(status,routeData){
  // console.log(status.value);
  // console.log(routeData)
  var payload = {
    "_id": routeData._id,
    "status":status.value,
  }
  // console.log(payload);

  this.contactService.updateRouteStatus(payload,routeData._id)
    .subscribe(res=>{
      // console.log("record updated!!!");
      // console.log(res);
    },err=>{
      // console.log("eError occured !!!")
    })
}

addRoute(){
 
  this.router.navigateByUrl("setRoute");
}
findByStatus:any;

getRoutebyStatus(state){
    this.findByStatus = state;
    this.tabelObj.ajax.reload();  
}

 untrack(data){

  if(this.dialog.openDialogs && this.dialog.openDialogs.length > 0){
      return false;
    }
    let dialogRef = this.dialog.open(TrackedVehiclesComponent, {
//  width: '503px',
//  height:'400px',
 data: data
 });
    dialogRef.afterClosed().subscribe((result) => {
      dialogRef = null;
      this.tabelObj.ajax.reload()
    if(result == "succ"){
      console.log("Updated")
    }
     
    });

 }
}
