// @ts-ignore
import { LOGIN_CONFIG } from "@/devLoginParams";

const { loginName, password, examId, markerId, isAdmin, forceChange } =
  LOGIN_CONFIG;

export async function initLogin() {
  if (document.cookie.includes("stmms_cookie") && !forceChange) return;
  const f = new FormData();
  f.append("loginType", isAdmin ? "admin-login" : "mark-login");
  f.append("loginName", loginName);
  f.append("password", password);

  return fetch("/login", { body: f, method: "POST" })
    .then(async (r) => {
      const body = await r.text();
      const exams = body.match(
        /<select name="examId" id="exam-select">.*<\/select>/gims
      );
      console.log(exams && exams[0].replace(/\n/g, ""));
    })
    .then(async () => {
      const f = new FormData();
      f.append("examId", examId);
      markerId && f.append("markerId", markerId || "");
      if (!isAdmin) {
        const res = await fetch("/mark/subject/query", {
          body: f,
          method: "POST",
        });
        console.log("markerId: ", await res.text());
      }
      return new Promise((resove) => {
        setTimeout(() => {
          const url = isAdmin ? "/admin/exam/select" : "/mark/subject-select";
          resove(fetch(url, { body: f, method: "POST" }));
        }, 1000);
      });
    });
  // .then(() => {
  //   console.log("login completed");
  //   return fetch("/mark/status");
  // })
  // .then(async (r) => {
  //   console.log(await r.json());
  //   return fetch("/mark/gettask");
  // })
  // .then(async (r) => {
  //   console.log(await r.json());
  // });
}
