import request from "requestretry";
// import env from "./env";
import _logger from "./logger";
const logger = _logger("api.js");
import fs from "fs/promises";

async function doIt(filepath: string) {
  const b = await fs.readFile(filepath);
  console.log(b.toString());
}

async function execute(uri, method, form) {
  // await new Promise((res) => setTimeout(res, 3000));
  console.log("sending...");
  console.log(uri, method, globalThis, globalThis.env);
  // console.log(globalThis.electron.env);
  // Object.assign(env, globalThis.electron.env);
  return new Promise((resolve, reject) => {
    request(
      {
        url: env.server.host + uri,
        method: method,
        json: true,
        timeout: 10000,
        form: form || {},
        headers: {
          "auth-info":
            "loginname=" + env.loginName + ";password=" + env.password,
        },
        maxAttempts: 50,
        retryDelay: 500,
        retryStrategy: request.RetryStrategies.HTTPOrNetworkError,
      },
      function (error, response, body) {
        if (response.statusCode == 200) {
          resolve(body);
        } else {
          const message =
            response.statusCode +
            " " +
            (error || "") +
            (response.headers["error-info"] || "");
          logger.error(message);
          reject(message);
        }
      }
    );
  });
}

export function login() {
  return execute("/api/user/login", "GET");
}

export function getExams(pageNumber, pageSize) {
  let uri = "/api/exams";
  const param = [];
  if (pageNumber != undefined) {
    param.push("pageNumber=" + pageNumber);
  }
  if (pageSize != undefined) {
    param.push("pageSize=" + pageSize);
  }
  if (param.length > 0) {
    uri = uri + "?" + param.join("&");
  }
  return execute(uri, "GET");
}

export function getStudents(examId, pageNumber, pageSize, params) {
  const form = {
    examId: examId,
    pageNumber: pageNumber,
    pageSize: pageSize,
  };
  if (params != undefined) {
    for (const key in params) {
      if (params[key] && params[key] != "") {
        form[key] = params[key];
      }
    }
  }
  return execute("/api/exam/students", "POST", form);
}

export function countStudents(examId, params) {
  params = params || {};
  params.examId = examId;
  return execute("/api/exam/students/count", "POST", params);
}

export function getPackages(examId, upload, withUrl) {
  let uri = "/api/package/count/" + examId;
  const param = [];
  if (upload != undefined) {
    param.push("upload=" + (upload ? "true" : "false"));
  }
  if (withUrl != undefined) {
    param.push("withUrl=" + (withUrl ? "true" : "false"));
  }
  if (param.length > 0) {
    uri = uri + "?" + param.join("&");
  }
  return execute(uri, "GET");
}

export default {
  execute,
  // login,
  getExams,
  getStudents,
  countStudents,
  getPackages,
  doIt,
};
