import { Component, OnInit } from '@angular/core';
import { ContactService } from '../../contact.service';

declare var $: any, DataTable: any;
import * as moment from 'moment'
@Component({
  selector: 'app-poi-report',
  templateUrl: './poi-report.component.html',
  styleUrls: ['./poi-report.component.scss']
})
export class POIReportComponent implements OnInit {
    
  option: any;
  Fromdate = new Date();
  todate = new Date();
  emailid: any;
  identifier = 'poi_report';
  useridd: any;
  tabelObj: any ;
  deviceName:any;
  routeName:any;
  constructor(public contactService: ContactService) { 
    this.emailid = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).email;
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
  }

  ngOnInit() {
    this.Fromdate.setHours(0, 0, 0);
    this.testTable();
    // this.getAllDevice();
    // this.getPOI();
    // this.searchFilter();
  }

 

testTable() {
    const that = this;
    // console.log("selectedRoute=>",this.routeSelect);
    $(document).ready(function() {
        that.tabelObj = $('#deviceTable').DataTable({
            serverSide: true,
            "processing": true,
            "searching": false,
            "pageLength": 25,
            "scrollY":'65vh',  
            "scrollCollapse": true,   
            ajax: (dataTablesParameters: any, callback) => {

                dataTablesParameters.op = {};
                dataTablesParameters.select = [];
                dataTablesParameters.find = {};
                // console.log(dataTablesParameters);
                // console.log("callback", callback);

                // dataTablesParameters.find = {
                //   _id: that.useridd         
                // };
                dataTablesParameters.columns = [
                    { data: "_id" },
                    { data: "device.Device_Name" },
                    { data: "device.Device_ID" },
                    { data: "address" },
                    { data: "arrivalTime" },
                    { data: "departureTime" },
                    { data: "poi.poi.poiname" },
                  ]
                //   console.log("selectedRoute=>",that.routeSelect);
                //   console.log("VehicleID",that.deviceSelect);

                // ==========================================
                if (that.Fromdate) {
                    var arrGtObj = { "arrivalTime": { "$gte": that.Fromdate } }
                    var depGtObj = { "departureTime": { "$gte": that.Fromdate } }
                }

                if (that.todate) {
                    var arrLtObj = { "arrivalTime": { "$lte": that.todate } }
                    var depLtObj = { "departureTime": { "$lte": that.todate } }
                }

                if (arrGtObj || arrLtObj) {
                    var arrAndObj1 = { "$and": [] }
                    if (arrGtObj)
                        arrAndObj1["$and"].push(arrGtObj);
                    if (arrLtObj)
                        arrAndObj1["$and"].push(arrLtObj);
                }

                if (depGtObj || depLtObj) {
                    var arrAndObj2 = { "$and": [] }
                    if (depGtObj)
                        arrAndObj2["$and"].push(depGtObj);
                    if (depLtObj)
                        arrAndObj2["$and"].push(depLtObj);
                }

                if (arrAndObj1 || arrAndObj2) {
                    var orArr = []
                    if (arrAndObj1)
                        orArr.push(arrAndObj1);
                    if (arrAndObj2)
                        orArr.push(arrAndObj2);
                }
                var finalObj = { "$or": orArr};
           
                dataTablesParameters.find = finalObj;
              
                if (that.deviceObj.length != 0){
                    // console.log(that.deviceSelect);
                    dataTablesParameters.find.device = that.deviceObj[0];        
                }

                if (that.poi_id.length != 0) {
                    
                    // console.log("routeId=>",that.routeSelect[0].id);              
                    dataTablesParameters.find.poi = that.poi_id[0];        
                }

                dataTablesParameters.find.user = that.useridd;


                var suburl = "";
                suburl += "/poi/datatable";
                // console.log(suburl);
                // console.log(dataTablesParameters);
                // console.log(suburl)
                that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {
                    console.log("poiResp",resp);
                    callback(resp);
                }, err => {           
                    // console.log(err.status);
                });
            },
            "columns": [
                {
                    "data": "device.Device_Name",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        return data ? data : "";
                    }
                },
                {
                    "data": "device.Device_ID",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        return data ? data : "";
                    }
                },
                {
                    "data": "poi.poi.poiname",
                    "defaultContent": "",
                    render: function(data, type, row) {
                        // console.log("poiData=>",data);
                        return data ? data : "";
                    }
                },
                {
                    "data": "arrivalTime",
                    "defaultContent": "",
                    render: function(data, type, row) {
                        var A_time = new Date(data);
                        return data ? (moment(A_time).format('llll')) : "";
                    }
                },
                {
                    "data": "departureTime",
                    "defaultContent": "",
                    render: function(data, type, row) {
                        var D_time = new Date(data);
                        return data ? (moment(D_time).format('llll')) : "";
                    }
                },
                {
                    "data": "address",
                    "defaultContent": "",
                    "render": function(data, type, row) {
                        var created_time = new Date(data);
                        return data?data:"";
                    }
                },             
            ],
        });

        that.tabelObj.columns().every( function () {
            var that = this;
     
            $( 'input', this.footer() ).on( 'keyup change', function () {
                if ( that.search() !== this.value ) {
                    that
                        .search( this.value )
                        .draw();
                }
            } );
        } );
       
    });

}


searchFilter(){
    // DataTable
    var table = $('#deviceTable').DataTable();
 
    // Apply the search
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );

}
deviceObj = [];
// getAllDevice() {
//     this.contactService.getDevice(this.emailid,this.useridd)
//         .subscribe(res => {
//             // console.log(res);
//             // console.log("allDevices=>", res);
//             this.deviceObj = [];
//             var Alldevices = {
//                 id: "all",
//                 viewValue: "ALL Devices"
//             }
//             this.deviceObj.push(Alldevices);

//             for (var i = 0; i < res.devices.length; i++) {
//                 Alldevices = {
//                     id: res.devices[i]._id,
//                     viewValue: res.devices[i].Device_Name ? res.devices[i].Device_Name : ""
//                 }

//                 this.deviceObj.push(Alldevices)
//             }
//             // console.log("deviceArray", this.deviceObj);

//         }, err => {
//             // console.log(err.status);
//         })
// }




deviceSelect: any = [];

filterDevices(dlr) {

    // console.log("deviceData=>", dlr);
    if (dlr) {
        // console.log(dlr);

        const filterdealerValue: any = dlr;

        this.deviceSelect = [];
        this.deviceSelect = this.deviceObj.filter(function(pp) {
         
            // console.log("dealerValue=>",pp);
            var t = pp.viewValue.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());

            return t > -1;
        });
        // console.log(this.deviceSelect);
        return this.deviceSelect;
    }

}

// Routename filter 
route_detail_show=[];
poiArr=[];
// getPOI(){
//     // console.log("Mapping history !!!");
//     this.contactService.getPOI(this.useridd)
//     .subscribe(res=>{
//     //   console.log("routedet",res);
//       this.route_detail_show=res;

//       var poiObj = {
//           poiname: "All POI",
//           id : "All"
//       }
//       this.poiArr.push(poiObj);
//       for(var i=0;i<this.route_detail_show.length;i++){
//         poiObj ={
//             poiname: this.route_detail_show[i].poi.poiname,
//             id : this.route_detail_show[i]._id
//           }

//           this.poiArr.push(poiObj);
//       }

//     //   console.log("routeDetails=>",this.poiArr);
//     })
//   }
  routeSelect=[];
//   filterRoutes(route_ID){
//     //   console.log(route_ID);
//       if (route_ID) {
//         //   console.log(route_ID);
//           const filterRouteValue: any = route_ID;
  
//           this.routeSelect = [];
          
//         //   console.log("routeData=>", this.route_detail_show);
//           this.routeSelect = this.poiArr.filter(function(rte) {
//             // console.log("routeObj=>",rte);
//               var r = rte.poiname.toLocaleLowerCase().indexOf(filterRouteValue.toLocaleLowerCase());     
//               return r > -1;
//           });
//         //   console.log("filtered route=>",this.routeSelect);
//           return this.routeSelect;
//       }

//   }

  tab:any;
  exportExcel()
{

    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];//document.getElementById('deviceTable'); // id of table

    for(j = 0 ; j < this.tab.rows.length ; j++) 
    {     
        tab_text=tab_text+this.tab.rows[j].innerHTML+"</tr>";
        // console.log('tab_text',JSON.parse(tab_text));
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    // tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    // tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

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

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

    return (sa);
}

  deviceArr :any=[];
  poi_id:any=[];
  getReport(event){
    if(event == 'getExcel'){
      this.exportExcel();
    }else{
        console.log(event);
      var deviceId: any;
      var tpdata = event ; 
      var that = this;
      var fd = new Date(tpdata.fromDate);
      var td  = new Date(tpdata.toDate);
      
      if(event.deviceArr.length==0){
        deviceId=[];
      }else{
        deviceId= event.deviceArr;
      }
      this.deviceObj = deviceId; 
      this.poi_id  = event.poi_id ;

      
      this.Fromdate = fd;
      this.todate = td;

      
      // this.tabelObj.clear();
      // var aa = [];
      // this.tabelObj.rows.add(aa);   
      this.tabelObj.draw(); 
        // this.tabelObj.ajax.reload();        
    }
   
  }

}
