import { Component, OnInit } from "@angular/core";
import { Http, Headers, Response, ResponseContentType } from "@angular/http";
import { environment } from "../../environments/environment";
import { map, mergeMap } from "rxjs/operators";
declare var $: any;
@Component({
  selector: "app-firmware",
  templateUrl: "./firmware.component.html",
  styleUrls: ["./firmware.component.scss"],
})
export class FirmwareComponent implements OnInit {
  dev_url = environment.hostUrl;
  dev_url2 = environment.hostUrl2;
  userToken = localStorage.getItem("token");
  headersVal = new Headers();
  constructor(private http: Http) {
    this.headersVal.append("Authorization", this.userToken);
  }
  dt: any = [];
  filter: any = {
    Device_ID: "",
    state: "",
  };
  tabelObj: any;
  search_flat: any = false;
  search(filter: any) {
    console.log(filter);
    this.tabelObj.ajax.reload();
  }
  ngOnInit() {
    let that = this;
    this.tabelObj = $("#db2023_deviceTable").DataTable({
      processing: true,
      searching: false,
      pagingType: "full_numbers",
      pageLength: 10,
      // dom: '<"row"<"col-6"l><"col-6"#d  wnl> <"col-12"t> <"col-6"i><"col-6"p>>',
      serverSide: true,
      // sort: false,
      // scrollY: "65vh",
      // scrollCollapse: true,
      lengthMenu: [
        [10, 25, 50, 99999999999999999999],
        [10, 25, 50, "All"],
      ],
      ajax: (dataTablesParameters, callback) => {
        let qr: any = {
          org: "6110fa23a6221d46dbebc473",
          page: Number(dataTablesParameters.start),
          limit: dataTablesParameters.length,
        };
        if (that.filter.Device_ID != "") {
          qr.Device_ID = that.filter.Device_ID;
        }
        if (that.filter.state != "") {
          qr.state = that.filter.state;
        }
        this.aj(qr).subscribe((resp) => {
          console.log(resp);
          that.dt = resp.data;
          callback({
            data: resp.data,
            recordsTotal: resp.recordsTotal,
            recordsFiltered: resp.recordsTotal,
          });
          // that.tabelObj.ajax.reload();
        });
      },

      columns: [
        {
          data: "Device_ID",
          title: "Device",
          defaultContent: "",
          render: function (data, type, row) {
            return data ? data : "";
          },
        },
        {
          data: "firmwareVersion",
          title: "Firmware Version",
          defaultContent: "",
          render: function (data, type, row) {
            return data ? data : "";
          },
        },
      ],
    });
  }

  aj(data) {
    let that = this;
    return this.http
      .post(this.dev_url + "/devices/getFirmwareVersion", data, {
        headers: this.headersVal,
      })
      .pipe(map((d: any) => d.json()));
  }
  getAllState = this.http
    .get(this.dev_url + "/RTO_master/getAllState", {
      headers: this.headersVal,
    })
    .pipe(map((d: any) => d.json()));
  convertJsonToCsv(data) {
    const csv = data.map((row) => Object.values(row).join(",")).join("\n");
    return `data:text/csv;charset=utf-8,${encodeURIComponent(
      "Device,Firmware Version\n" + csv
    )}`;
  }

  // Create a download link for the CSV file
  downloadCsv(data, filename) {
    const csvData = this.convertJsonToCsv(data);
    const link = document.createElement("a");
    link.setAttribute("href", csvData);
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}
