import { Component, OnInit } from "@angular/core";
import { ContactService } from "../contact.service";
import { BsDatepickerConfig } from "ngx-bootstrap";
import { Location } from "@angular/common";
import { Router } from "@angular/router";
import { CommandWindowComponent } from "../location/command-window/command-window.component";
import { CmdUIComponent } from "../location/cmd-ui/cmd-ui.component";
import {
  MdDialog,
  MdDialogRef,
  MD_DIALOG_DATA,
  MdTabChangeEvent,
} from "@angular/material";
import { RawDataCommandComponent } from "../raw-data-command/raw-data-command.component";
import { GprsCommndTablePopupComponent } from "../gprs-commnd-table-popup/gprs-commnd-table-popup.component";
// import * as bootstrap from 'bootstrap';
// import { Popover } from 'bootstrap';
declare var $: any, moment: any;
declare var swal: any;
@Component({
  selector: "app-raw",
  templateUrl: "./raw.component.html",
  styleUrls: ["./raw.component.scss"],
})
export class RawComponent implements OnInit {
  baseUrl: string;
  constructor(
    private cs: ContactService,
    private router: Router,
    private dialog: MdDialog
  ) {}
  bsConfig: Partial<BsDatepickerConfig>;
  fromDate = new Date();
  toDate = new Date();
  imei: any = "";
  dt: any = {};
  qr: any = {
    search: false,
    skip: 0,
    limit: 10,
  };

  Copy_Data: any = [{}];
  CopyData(i: any) {
    this.Copy_Data = i;
    console.warn(this.Copy_Data.raw);
    // this.copyTextToClipboard(this.Copy_Data.raw);
    this.copyToClipboard(this.Copy_Data.raw);
    // swal.fire({
    //   position: 'top-end',
    //   icon: 'success',
    //   text: "Data Copied to Clipboard",
    //   showConfirmButton: false,
    //   toast: true,
    //   timer: 1000,
    // });
  }
  date(dt, fmt) {
    return moment(dt.createdAt).format(fmt);
  }
  db_date(dt, fmt) {
    return moment(dt).format(fmt);
  }
  changeDate() {}
  search() {
    this.qr.search = true;
    $("#example").DataTable().ajax.reload();
  }
  ngOnInit() {
    this.navigateToBaseURL();
    let that = this;
    var fTime = new Date();
    fTime.setHours(0, 0, 0, 0);
    this.fromDate = new Date(fTime);

    let colorTheme = "theme-dark-blue";
    this.bsConfig = Object.assign(
      { dateInputFormat: "DD-MM-YYYY, h:mm:ss a" },
      { containerClass: colorTheme }
    );
    this.dt = $("#example").DataTable({
      processing: true,
      sort: false,
      serverSide: true,
      pagingType: "full_numbers",
      ajax: (dataTablesParameters: any, callback: any) => {
        let qr: any = {};
        /*         if (that.qr.search == true) {
          if (that.imei != "") qr.imei = that.imei;
          qr.from = that.fromDate;
          qr.to = that.toDate;
          that.qr.search = false;
        } else {
          that.qr.imei = dataTablesParameters.search.value;
        } */
        /*  */
        if (that.qr.search == false) {
          /*  */
          qr.skip = dataTablesParameters.start;
          qr.limit = dataTablesParameters.length;
          that.qr.search == true;
        } else if (that.qr.search == true) {
          if (that.imei != "") qr.imei = that.imei;
          // qr.from = that.fromDate;
          // qr.to = that.toDate;

          that.qr.imei = dataTablesParameters.search.value;
          /*  */
          qr.skip = dataTablesParameters.start;
          qr.limit = dataTablesParameters.length;
        }

        that.cs
          // .db_ajaxURL("/pings", qr)
          .db_ajaxURL("/pingsv2", qr)
          // .db_ajax("https://www.oneqlik.in/use/pingsv2", qr)
          .subscribe((resp: any) => {
            console.log("pings=>", resp);
            console.log("Raw data check=>", resp.data);
            callback({
              recordsTotal: resp.recordsTotal,
              recordsFiltered: resp.recordsTotal,
              data: resp.data,
            });
          });
      },
      // rowCallback: (row: Node, data: any[] | Object, index: number) => {
      //   debugger
      //   const self = this;
      //   $('td', row).off('click');
      //   $('td', row).on('click', () => {
      //     self.CopyData(data);
      //   });
      //   return row;
      // },

      rowCallback: (row: Node, data: any[] | Object, index: number) => {
        debugger;

        const self = this;
        $("td", row).off("click");

        // Type assertion to let TypeScript know that 'data' has a 'raw' property
        const dataWithRaw = data as { raw?: string }; // '?' indicates that 'raw' is optional

        // Find the copy icon within the cell
        const copyIcon = $("td .fa-copy", row);
        const sendCommandIcon = $("td .fa-terminal", row);
        const openCommandTableIcon = $("td .fa-up-right-from-square", row);
        // Add a click event listener to the copy icon
        copyIcon.on("click", () => {
          // Check if 'raw' property exists before calling CopyData
          if (dataWithRaw !== undefined) {
            self.CopyData(dataWithRaw);
          } else {
            console.error("Raw property is undefined.");
          }
        });

        sendCommandIcon.on("click", () => {
          // Check if 'raw' property exists before calling CopyData
          if (dataWithRaw !== undefined) {
            self.triggerDeviceCmd(dataWithRaw);
          } else {
            console.error("Raw property is undefined.");
          }
        });

        openCommandTableIcon.on("click", () => {
          // Check if 'raw' property exists before calling CopyData
          if (dataWithRaw !== undefined) {
            self.triggerDeviceCmdTable(dataWithRaw);
            console.log(
              "CopyData function called with raw data:",
              dataWithRaw.raw
            );
          } else {
            console.error("Raw property is undefined.");
          }
        });
      },

      columns: [
        { data: "imei" },
        {
          data: "updatedAt",
          render: function (data, type, row) {
            debugger;
            return data
              ? `<span class="text-nowrap">${that.db_date(
                  row.updatedAt,
                  "DD-MM-YYYY hh:mm:ss"
                )}</span>`
              : "";
          },
        },

        /*         {
          data: "Updated",
          render: function (data, type, row) {
            return data
              ? `<span class="text-nowrap">${that.date(
                  data,
                  "DD-MM-YYYY hh:mm"
                )}</span>`
              : "";
          },
        }, */

        // {
        //   data: "updatedAt",
        //   render: function (data, type, row) {
        //     return data
        //       ? `<span class="text-nowrap">${that.date(
        //           data,
        //           "DD-MM-YYYY hh:mm"
        //         )}</span>`
        //       : "";
        //   },
        // },
        {
          data: "remarks",
          render: function (data, type, row) {
            return data
              ? `<div style="display: flex; align-items: center;">
            <span title="${data}" class="db_remarks">${data}</span>
                        </div>`
              : // ? `<span title="${data}"class='db_text'>${data}</span><span style="pointer:cursor"><i class="fa-solid fa-copy"></i></span>`
                "";
          },
        },
        {
          data: "raw",
          render: function (data, type, row) {
            return data
              ? `<div style="display: flex; align-items: center;">
            <span title="${data}" class="db_text">${data}</span>
            <span style="cursor: pointer; margin-left: 5px;"><i class="fa-solid fa-copy" style="font-size: 1.2rem;" title="Copy raw data"></i></span>
            <span style="cursor:pointer; margin-left:3px"><i class="fas fa-terminal" style="cursor:pointer;color: black;margin-left: 5px;" title="Trigger Command"></i> </span>
            <span style="cursor:pointer; margin-left:3px"><i class="fa-solid fa-up-right-from-square" style="cursor:pointer;color: black;margin-left: 5px;" title="View Command List"></i> </span>
            </div>`
              : // ? `<span title="${data}"class='db_text'>${data}</span><span style="pointer:cursor"><i class="fa-solid fa-copy"></i></span>`
                "";
          },
        },
        // {
        //   data:null,
        //    render: function (data, type, row) {

        //     // $(row).find('.fa-clipboard').on('click', () => {
        //     //   this.copyToClipboard(row.raw); });
        //     return `<button class="btn btn-primary" (click)="copyToClipboard(row.raw)">Copy Raw Data</button>`;
        //   }

        // },
        // { data: "port" },
        // { data: "ip" },
      ],
    });

    // tooltip
    // var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
    // var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    //   return new bootstrap.Tooltip(tooltipTriggerEl)
    // })
  }

  private navigateToBaseURL() {
    this.router.navigateByUrl("/raw");
  }
  copyToClipboard(text: string): void {
    const textField = document.createElement("textarea");
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand("copy");
    textField.remove();
  }
  tab: any;
  exportToExcel() {
    console.log("IN EXPORT");
    var tab_text = "<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange;
    var j = 0;
    var table = $("#example").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;
  }

  triggerDeviceCmd(dev) {
    //  CmdUIComponent
    let dialogRef = this.dialog.open(RawDataCommandComponent, {
      width: "500px",
      data: { deviceObject: dev },
    });

    // dialogRef.afterClosed().subscribe((result) => {
    //   if (result == "succ") {

    //     launch_toast();
    //   }

    //   if (result == "openOther") {
    //     let dialogRef_1 = this.dialog.open(CmdUIComponent, {
    //       width: "500px",
    //       data: { deviceObject: dev },
    //     });
    //     dialogRef_1.afterClosed().subscribe((result) => {
    //       if (result === "cancel") {
    //         // console.log('Working Fine');
    //       }

    //       if (result === "succ") {

    //         launch_toast();
    //       }
    //     });
    //   }
    //   function launch_toast() {
    //     var x = document.getElementById("toast");
    //     x.className = "show";
    //     setTimeout(function () {
    //       x.className = x.className.replace("show", "");
    //     }, 1500);
    //   }
    // });
  }
  triggerDeviceCmdTable(dev) {
    //  CmdUIComponent
    let dialogRef = this.dialog.open(GprsCommndTablePopupComponent, {
      width: "1200px",
      data: { deviceObject: dev },
    });
  }
}
