import { Injectable } from "@angular/core";
import { Http, Headers, Response, ResponseContentType } from "@angular/http";
import { environment } from "../../environments/environment";
import { map, mergeMap } from "rxjs/operators";

@Injectable()
export class FotaService {
  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);
  }
  bulkcommand_trigger(data) {
    let that = this;
    return this.http
      .post(this.dev_url + "/bulkCommand/trigger", data, {
        headers: this.headersVal,
      })
      .pipe(map((d: any) => d.json()));
  }
  bulkcommand_list(data: any) {
    return this.http
      .post(this.dev_url + "/bulkCommand/list", data, {
        headers: this.headersVal,
      })
      .pipe(map((d: any) => d.json()));
  }
  bulkCommand_triggeredCommands(data: any) {
    let that = this;
    return this.http
      .post(this.dev_url + "/bulkCommand/triggeredCommands", data, {
        headers: this.headersVal,
      })
      .pipe(map((d: any) => d.json()));
  }
  bulkcommand_commanddetails(data: any) {
    let that = this;
    return this.http
      .post(this.dev_url + "/bulkCommand/commandDetails", data, {
        headers: this.headersVal,
      })
      .pipe(map((d: any) => d.json()));
  }

  convertJSONToCSV(jsonData) {
    const separator = ",";
    const keys = Object.keys(jsonData[0]);

    const csvContent = [
      keys.join(separator),
      ...jsonData.map((item) => keys.map((key) => item[key]).join(separator)),
    ].join("\n");

    return csvContent;
  }

  downloadCSV(csvContent, fileName) {
    const blob = new Blob([csvContent], { type: "text/csv" });
    const url = URL.createObjectURL(blob);

    const a = document.createElement("a");
    a.href = url;
    a.download = fileName;
    a.click();

    URL.revokeObjectURL(url);
  }
}
