class Logger {
  constructor() {
    this.prefix = "spi";

    this.storageKey = "spi-logs";

    // Current log record lines
    this.linesCount = 0;

    // maximum number of logs to show
    this.maxLogCount = 1000;

    this.debugout = new Debugout({
      useLocalStorage: true,
      useTimestamps: true,
      includeSessionMetadata: false,
      realTimeLoggingOn: false,
      indent: "",
      localStorageKey: this.storageKey,
    });
  }

  // clear logs
  clear() {
    this.linesCount = 0;
    this.debugout.clear();
    window.localStorage.removeItem(this.localStorageKey);
  }

  // add log message to the log list and also output it on the console
  info(...p) {
    this.debugout.info(...p);
    this.linesCount++;
    if (this.linesCount === this.maxLogCount) {
      this.saveLogs();
      this.linesCount = 0;
    }
  }

  getLogs() {
    let logs = null;
    try {
      logs = window.localStorage.getItem(this.storageKey);
    } catch (error) {
      console.debug(">>> logger.getLogs error:", error);
    }
    return logs;
  }

    async saveLogs() {
        console.debug(">>> logger.saveLog start");
        const output = this.getLogs();
        if (output == null || output == "") {
            return;
        }
        const request = {};
        request.MachineID = machineID;
        request.LogKey = formatDate(new Date());
        request.LogText = output;

        try {
            const result = await $.ajax({
                type: "POST",
                headers: {
                    Accept: "application/json; charset=utf-8",
                    ContentType: "application/json; charset=utf-8",
                    MerchantId: zmerchantId,
                    BranchId: zbranchId,
                },
                url: `/api/eft/saveLog`,
                data: JSON.stringify(request),
                dataType: "json",
                contentType: "application/json;charset=UTF-8",
            });

            console.debug(">>> logger.saveLog response.result:", result);

            if (result.Code == "1000") {
                this.clear();
            } else {
                console.debug(">>> logger.saveLog response fail:", result.Message);
            }
        } catch (error) {
            console.debug(">>> logger.saveLog response error:", error);
        }
    }

    download(date) {
        const { protocol, host } = window.location;
        const url = `${protocol}//${host}/eftui/downloadlog?merchantId=${zmerchantId}&branchId=${zbranchId}&machineID=${machineID}&Seq=${Seq}&date=${formatDate(
            date
        )}`;
        //TODO: change bridge implement.
        // window.openBrowser.postMessage(url);
        window.hybridAPP.openBrowser(url);
    }
}
