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

declare var $: any, DataTable: any;
import * as moment from 'moment';
@Component({
  selector: 'app-cmd-packet-master',
  templateUrl: './cmd-packet-master.component.html',
  styleUrls: ['./cmd-packet-master.component.scss']
})
export class CmdPacketMasterComponent implements OnInit {
  option: any;
  Fromdate = new Date();
  todate = new Date();
  tabelObj: any;
  emailid: any;
  useridd: any;
  supadm: any;
  constructor(public contactService: ContactService) {
    this.Fromdate.setHours(0, 0, 0);
    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.supadm = JSON.parse(window.atob(window.localStorage.token.split(".")[1])).isSuperAdmin;

  }

  ngOnInit() {
    
    this.testTable();
    this.getAllDevice();
  }

  callfunction(): void {
    this.tabelObj.draw();
  }


  testTable() {
    const that = this;

    $(document).ready(function () {
      that.tabelObj = $('#cmdTable').DataTable({
        "serverSide": true,
        "processing": true,
        "searching": false,
        ajax: (dataTablesParameters: any, callback) => {

          dataTablesParameters.op = {};
          dataTablesParameters.select = [];
          dataTablesParameters.find = {};
          // dataTablesParameters.order = [{column: 3, dir: "desc"}];


          // console.log(dataTablesParameters);
          // console.log("callback", callback);

          // dataTablesParameters.find = {
          //   _id: that.useridd         
          // };
          dataTablesParameters.columns = [
            { data: "device_id" },
            { data: "protocal_id" },
            { data: "cmd" },
            { data: "insertionTime" },
            { data: "ACC" },
            { data: "batteryStatus" },
            { data: "gsmSignal" }]

        //    dataTablesParameters.find.supAdmin = that.useridd;

          if ((that.deviceSelect) && (that.deviceSelect != '') && (that.deviceSelect[0].id != "all")) {
            // console.log(that.deviceSelect[0].id);
            dataTablesParameters.find.device_id = that.deviceSelect[0].id;
          }
          if (that.Fromdate) {
            that.Fromdate.setHours(0,0,0,0);
            dataTablesParameters.find['insertionTime'] = dataTablesParameters.find['insertionTime'] ? dataTablesParameters.find['insertionTime'] : {};
            dataTablesParameters.find['insertionTime']['$gte'] = {
              _eval: 'date',
              value: new Date(that.Fromdate).toISOString()
            }
          };
          // }
          if (that.todate) {
            that.todate.setSeconds(0);
            that.todate.setMilliseconds(0);
            dataTablesParameters.find['insertionTime'] = dataTablesParameters.find['insertionTime'] ? dataTablesParameters.find['insertionTime'] : {};
            dataTablesParameters.find['insertionTime']['$lte'] = {
              _eval: 'date',
              value: new Date(that.todate).toISOString()
            };
          }
          // if(this.supadm){
          //   dataTablesParameters.find.supAdmin = that.useridd;
          // }
          var suburl = "";
          suburl += "/cmdPackets/datatable";
          // console.log(suburl);
          // console.log(dataTablesParameters);
          // console.log(suburl)
          that.contactService.post(suburl, dataTablesParameters).subscribe(resp => {

            callback(resp);

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

        "columns": [
          {
            "data": "device_id",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "protocal_id",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "cmd",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "insertionTime",
            "render": function (data, type, row) {
              var created_time = new Date(data);

              return moment(created_time).format('dddd,ll,LTS');
            }
          },
          {
            data: "ACC",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          },
          {
            "data": "batteryStatus",
            "render": function (data, type, row) {

              return data ? data : "";
            }
          },
          {
            "data": "gsmSignal",
            "render": function (data, type, row) {
              return data ? data : "";
            }
          }
        ],
        columnDefs: [
          {
            // The `data` parameter refers to the data for the cell (defined by the
            // `data` option, which defaults to the column being worked with, in
            // this case `data: 0`.

          },
        ]
      });
    });

  }


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

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

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

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


  deviceSelect: any = [];
  deviceName: 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(pp);
        var t = pp.viewValue.toLocaleLowerCase().indexOf(filterdealerValue.toLocaleLowerCase());

        return t > -1;
      });
      return this.deviceSelect;
    }

  }


  filterStates(option) {
    // console.log(option);
  }
}
