import { Component, Inject, OnInit } from '@angular/core';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';
declare var $:any;
import * as moment from 'moment';

@Component({
  selector: 'app-select-untrack-vehicles',
  templateUrl: './select-untrack-vehicles.component.html',
  styleUrls: ['./select-untrack-vehicles.component.scss']
})
export class SelectUntrackVehiclesComponent implements OnInit {
  emailid: any;
  useridd: any;
  devicesss: any;
  uncheckedArr=[];
  tabelObj: any;
  poiDevices=[];
  untrackedDev=[];
  tempArray: any[];
  selectedDevices: any[];
  notSelectedPOIArray=[];
  Load: boolean;
  changed:boolean=true
  superAdmin: any;
  trackedDevices
 constructor(public dialogRef: MdDialogRef<SelectUntrackVehiclesComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private contactService:ContactService) {
      console.log(data);
      // this.untrackedDev=data.untrackedDevice?data.untrackedDevice:[]
      var deviceIDs = data.untrackedDevice?data.untrackedDevice:[];
      this.trackedDevices=data.trackedDevice?data.trackedDevice:[];
        //  console.log(deviceIDs);
        if(deviceIDs.length != 0){
         for(var k =0; k<deviceIDs.length;k++){
          //  console.log(deviceIDs[k])
           this.untrackedDev.push(deviceIDs[k]);
          }
          console.log("untrackedDevice=>",this.untrackedDev);
        }
         this.notSelectedPOIArray = this.untrackedDev;
     }

  ngOnInit() {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
  script.setAttribute("src", "https://unpkg.com/multiple-select@1.3.1/dist/multiple-select.min.js");
  document.getElementsByTagName("head")[0].appendChild(script);
  setTimeout(() => {
    // $('#dbselectIMEI').multipleSelect({
        //   width: 250,
        //   placeholder: "Vehicle IMEI",
        //   filter: true,
        //   single: true,
        //   selectAll: false  
        // }) 
  
        $('#dbselectVehicleName').multipleSelect({
          width: 250,
          placeholder: "Vehicle Name",
          filter: true,
          single: true,
          selectAll: false  
        }) 
        
        // $("#dbselectVehicleName").multipleSelect("disable");
        
      },100)
       this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
     this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
      this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id; 
        // this.getUserDevices();
        this.testTable()
  }


  change(obj: any,ind:any){ 
    console.log(obj, ind);
    
    this.poiDevices[ind].isTrue = this.poiDevices[ind].isTrue?!this.poiDevices[ind].isTrue:true;
    var i = this.notSelectedPOIArray.indexOf(obj.id);
    
    if( i==-1)
      this.notSelectedPOIArray.push(obj.id);
    else{
      
        this.notSelectedPOIArray.splice(i,1);  
    }
      console.log(this.notSelectedPOIArray); 
  }

  update(){

    console.log(this.data,this.trackedDevices.length)
     const newGeo ={
            uid: this.useridd,
            geofence:this.data.geofence.coordinates,
            geoname: this.data.geoname,
            entering:this.data.entering,
            exiting:this.data.exiting,
            // vehicleGroup:grp[0],
            type:this.data.type,
            _id:this.data._id,
            untrackedDevice:this.notSelectedPOIArray,
            trackedDevice:this.trackedDevices   
          }
          this.contactService.updateGeo(newGeo).subscribe(devgeo => {
              // localStorage.removeItem("cordinates");
              // this.router.navigateByUrl("geofencing");
              this.dialogRef.close()
              // this.geoadd.push(devgeo);
            }, (err: any) => { 
  
            });
  }

  testTable() {
    const that = this;
    console.log("inside function");
    $(document).ready(function () {
      that.tabelObj = $('#deviceTable').DataTable({
        // dom: 'Bfrtip',
        // buttons: [ 'copy', 'csv', 'ex  cel', 'pdf', 'print' ],
        "autoWidth": true,
        'deferRender':true,
        "processing": true,
        stateSave: true,
        "bDestroy": true,
        "searching": true,
        pagingType: 'full_numbers',
        pageLength: 25,
        serverSide: false,
        "scrollX": true,
        "scrollY": '65vh',
        "scrollCollapse": true,
        lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
        "createdRow": function(row: Node, data: any | Object, index: number){
        //  "rowCallback": function(row: Node, data: any | Object, index: number){
          $('#edit', row).bind('click', () => {   
           
                console.log(data);
            var ind=that.poiDevices.indexOf(data)
              console.log(that.poiDevices[ind],ind);
            that.poiDevices[ind].isTrue = that.poiDevices[ind].isTrue?!that.poiDevices[ind].isTrue:true;
           var i = that.notSelectedPOIArray.indexOf(data.id);
            var index=that.trackedDevices.indexOf(data.id);
            console.log(index==-1);
            
            if(index==-1){
              if(!that.trackedDevices.includes(data.id)){
                console.log(that.trackedDevices.length);
                
                console.log("In tracked Device");
                
                that.trackedDevices.push(data.id);
                console.log(that.trackedDevices.length);
              }
              if(that.notSelectedPOIArray.includes(data.id)){
                 that.notSelectedPOIArray.splice(i,1);
              }
              
            }else{
               console.log("In Untracked Device");
              if(!that.notSelectedPOIArray.includes(data.id)){

                that.notSelectedPOIArray.push(data.id);
              }
              if(that.trackedDevices.includes(data.id)){
                 console.log(that.trackedDevices.length,i);
                 that.trackedDevices.splice(index,1);
                  console.log(that.trackedDevices.length);
              }

              // that.trackedDevices.splice(index,1);
              // that.notSelectedPOIArray.push(data.id);
            }
            // if( i==-1){
            //  that.notSelectedPOIArray.push(data.id);
            // }
            // else{
            //   that.trackedDevices.push(data.id);
            //   that.notSelectedPOIArray.splice(i,1);  
            // }
      console.log(that.notSelectedPOIArray,that.trackedDevices); 
      
         })
        },
        ajax: (dataTablesParameters, callback) => {
           that.Load = true;
          var suburl = '/devices/getDeviceByUser?email='+that.emailid+'&id='+that.useridd+'&limit=all';
          if(that.superAdmin){
             suburl = '/devices/getDeviceByUser?email='+that.emailid+'&id='+that.useridd+'&limit=all&supAdmin='+that.useridd;
          }
          if(that.changed){
            that.contactService.get(suburl).subscribe((res:any)=>{
        
        that.devicesss=res.devices;
       for(var i = 0; i<res.devices.length ; i++){       
            var dev = {
              isTrue:true,
              id:res.devices[i]._id,
              Device_Name: res.devices[i].Device_Name,
              Device_ID:res.devices[i].Device_ID
            }  
          that.poiDevices.push(dev);  
      //     // that.notSelectedPOIArray.push(res.devices[i]._id)        
        }   
      var finalArr=[]  ;
      var j=0 
      for (var i = 0; i < that.poiDevices.length; i++) {
                    that.clocation_1(that.poiDevices[i], function (err, succ) {
                      if (err) {
                        console.log(err);
                        j++;
                      } else {
                        // console.log(succ);
                        succ['index']=j
                        finalArr.push(succ);
                        // console.log(finalArr,j);
                        j++;
                        if (j === that.poiDevices.length) {
                          that.Load = false;
                          callback({ data: finalArr });
                        }
                      }
                    })
    
                   
                  }
         that.Load = false;
         })
        }else{
          // console.log(that.poiDevices);
          
          callback({ data: that.poiDevices});
           that.Load = false;
           that.changed=true
        }

        },

        "columns": [
          {
            "data": "isTrue",
            "render": function (data, row) { 
              if(data){
                return "<input checked type='checkbox' id='edit'>"   
              } else{
                 return "<input  type='checkbox' id='edit'>" 
              }
            }
          },
           {
            "data": "Device_Name",
            "render": function (data, row) {  
              return data?data:'N/A';   
            }
          },
          {
            "data": "Device_ID",
           
            "render": function (data, row) {             
              return data;   
            }
          },
         
          
        ],
        "columnDefs": [
          { className: "dt-body-left", "targets": [0,1,2] },
          {
            "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 },

        ], order: [[ 0, 'desc' ], [ 0, 'asc' ]]
      });
  //     $('#deviceTable tbody').on('change', 'input[type="checkbox"]', function(e){
  //     // If checkbox is not checked
  //     console.log("dis",e);
      
  //     if(!this.checked){
  //        var el = $('#example-select-all').get(0);
  //        console.log(el);
         
  //        // If "Select all" control is checked and has 'indeterminate' property
  //        if(el && el.checked && ('indeterminate' in el)){
  //           // Set visual state of "Select all" control 
  //           // as 'indeterminate'
  //           el.indeterminate = true;
  //        }
  //     }
  //  });  
  //  $(".deviceTable").on('change', 'input[type="checkbox"]', function(e) {
  //   var attendance = {
  //     name: $(this).closest("tr").find("td:nth-child(1)")
  //   };
  //   console.log(attendance);
  // });

    });

  }
  selectAll(event){
    this.changed=false
    // console.log(event);
    
    if(event.target.checked){
      for(var i=0;i<this.poiDevices.length;i++){
      this.poiDevices[i].isTrue=true;
      this.trackedDevices.push(this.poiDevices[i].id)
     
    }
      this.notSelectedPOIArray=[];
    }else{
      for(var i=0;i<this.poiDevices.length;i++){
        this.poiDevices[i].isTrue=false
         this.notSelectedPOIArray.push(this.poiDevices[i].id)
      }
       
       this.trackedDevices=[]
    }
    this.tabelObj.ajax.reload();
    
    console.log(this.notSelectedPOIArray,this.trackedDevices);
  }

   clocation_1(latlngObj, cb) {
     if(latlngObj==null){
       cb(null, latlngObj);
     }
    //  console.log(latlngObj);
     
     if(this.trackedDevices.includes(latlngObj.id)){
        latlngObj.isTrue=true;
        cb(null, latlngObj);
     }else{
        latlngObj.isTrue=false;
          cb(null, latlngObj);
     }
     }
    
   

  }



