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 {DeviceModel} from '../device-model';
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 { EditDeviceModelComponent } from '../edit-device-model/edit-device-model.component';
import { FlashMessagesService } from 'angular2-flash-messages';
declare var $: any;

declare var google: any;
declare var swal: any;
declare var moment:any;

@Component({
  selector: 'app-device-model',
  templateUrl: './device-model.component.html',
  styleUrls: ['./device-model.component.css'],
  providers: [ContactService,SidebarComponent]
})
export class DeviceModelComponent implements OnInit {
  modelChanged: Subject<string> = new Subject<string>();
  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=[];

deviceModels:any=[];
deviceModel: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;
  orgChk: any;
  custtype: any;
  tabelObj: any;

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

    this.superAdmin = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;
    this.orgChk = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isOrganisation ; 
    this.adbtn = localStorage.getItem("dlrchk")

    this.sidebar.sidebarData();
  
    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.getDeviceModel();
      this.testTable();

  }

// deleteRecord(data){

//   swal({
//     title: 'Are you sure?',
//     text: "You won't be able to revert this!",
//     type: 'warning',
//     showCancelButton: true,
//     confirmButtonColor: '#3085d6',
//     cancelButtonColor: '#d33',
//     confirmButtonText: 'Yes, delete it!'
//   }).then((result: { value: boolean; }) => {
//     if (result) {
//       this.contactService.deleteDeviceModel(data).subscribe(
//         data => {
//           this.deviceModels=[];
//           this.deviceModel=[];
//           // this.getDeviceModel();
//           swal(
//             'Deleted!',
//             'Your file has been deleted.',
//             'success'
//           )
//         },err=>{
//           swal(
//             'Server Error',
//             'Error occured while deleting device configuration , Please try after sometime !!!',
//             'error'
//           )
//         });    
//     }
//   })


// }

add_DeviceModel(){
 

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

}

  



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;
mb:any;
logoutbut:boolean;
dealer:boolean;
logo:any;
text:any;
data_to_view=[];
Durations:any;
superAdmin:Boolean = false;


  skip=0;
  limit=1000000;
  myInput:any;

  // getDeviceModel(){
  //   this.deviceModel = [];
     
  //   this.contactService.getDeviceModel(this.skip, this.limit,this.myInput).subscribe( 
  //     data => {
  //      for(let i=0;i<data.length;i++){
  //       this.deviceModel.push(data[i]); 
  //       }
  
  //     });
      
  // }

  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,
            "scrollX": true,
            "scrollY": "500px",
            "scrollCollapse": 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 += "/deviceModel/getDeviceModel";
              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){
            $('#editModel',row).bind('click',()=>{  
                    console.log(data);

                  if(that.dialog.openDialogs && that.dialog.openDialogs.length > 0){
                      return false;
                    }
                    let dialogRef = that.dialog.open(EditDeviceModelComponent, {
                      data : data
                    });
                  
                    dialogRef.afterClosed().subscribe(result => {
                      console.log(result);
                      // console.log(result);
                      if (result == "success") {
                        that.tabelObj.ajax.reload();     
                      }
                    
                    });
          })
            $('#deleteModel',row).bind('click',()=>{  
              swal({
                  // title: 'Are you sure?',
                  text: "Do you want to delete Device model?",
                  type: 'warning',
                  showCancelButton: true,
                  confirmButtonColor: '#3085d6',
                  cancelButtonColor: '#d33',
                  confirmButtonText: 'Yes, delete'
                }).then((result: { value: boolean; }) =>{                      
                  if(result){
                    console.log(data._id);
                 
                    that.contactService.deleteDeviceModel(data._id).subscribe(  
                      data => {  
                         
                        swal(
                          'Deleted',
                          'Device Model deleted',
                          'success'
                        )

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

            },
        
            "columns": [
              {
                "data": "_id",
                "visible":false,
                "defaultContent": "",
                "render": function(data, type, row) {  
                  return data?data : '';                  
                }
            },
            {
              "data": "device_type",
              "defaultContent": "",
              "render": function(data, type, row) {  
                return data?data : '';                  
              }
          },
          
              {
                "data": "configuration_command",
                "defaultContent": "",
                "render": function(data, type, row) {  
                  return data?data : '';                  
                }
            },
                {
                    "data": "location_command",
                    "defaultContent": "",
                    "render": function(data, type, row) {  
                      return data?data : '';                  
                    }
                },
                {
                    "data": "immoblizer_command",
                    "defaultContent": "",
                    render: function(data, type, row) {
                     return data?data:''; 
                    }
                }, 
                {
                  "data": "resume_command",
                  "defaultContent": "",
                  render: function(data, type, row) {
                    return data?data:'';        
                  }
              }, 
                {
                  "data": "reset_command",
                  "defaultContent": "",
                  render: function(data, type, row) {
                  
                    return data ? data : "";  
                  }
              }, 
         
            {                
              "data":"imobliser_type",
              "defaultContent": "",
              "render":function(data,type,row){  
                return data ? data : "";  
              }
          } ,   
          {                
            "data":"deviceport",
            "defaultContent": "",
            "render":function(data,type,row){  
              return data ? data : "";  
            }
        },
        {                
            "data":"sms_apn",
            "defaultContent": "",
            "render":function(data,type,row){  
              return data ? data : "";  
            }
        },
        {                
            "data":"sms_ip",
            "defaultContent": "",
            "render":function(data,type,row){  
              return data ? data : "";  
            }
        },
        {                
            "data":"sms_timezone",
            "defaultContent": "",
            "render":function(data,type,row){  
              return data ? data : "";  
            }
        },   
          {                
            "data":null,
            "defaultContent": "",
            "render":function(data,type,row){  
                return '<i id="editModel" class="fas fa-edit" style="cursor:pointer;color:green" title="Edit Model"></i>'
            }
        }  
        ,   
          {                
            "data":null,
            "defaultContent": "",
            "render":function(data,type,row){  
                return '<i id="deleteModel" class="fas fa-trash" style="cursor:pointer;color:green" title="Delete Model"></i>'
            }
        }                      
            ],  

        });

        
        that.colSwitch()

  
    });
  
  }

   editDeviceModel(data){
    
    let dialogRef = this.dialog.open(EditDeviceModelComponent, {
      data : data
    });
  
    dialogRef.afterClosed().subscribe(result => {
      console.log(result);
      // console.log(result);
      if (result == "success") {
        // this.tost1("succ");
    //   this._flashMessagesService.show('Model Updated !!!', { cssClass: 'alert-success', timeout: 2000 });
          //  this.getDeviceModel();
      }
    
    });
   
   }


   colSwitch() {
   
        for (var k = 0; k <= 11; k++) { 
          this.tabelObj.column(0).visible(false);
          if (this.orgChk != true ) {
            if ((k == 9) || (k == 10)) {
              this.tabelObj.column(k).visible(false);
          } else{
            this.tabelObj.column(k).visible(true);
          }  
          }        
                       
            }
        
    }
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);
  }
  
}



