import { apiFormatDate } from "./dengi";

export async function makeRequest(url, params) {
  try {
    const req = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams(params).toString(),
    });

    return req.ok &&
      req.headers.get("Content-Type")?.includes("application/json")
      ? [1, await req.json()]
      : [req.status, await req.text()];
  } catch (err) {
    return [-1, err];
  }
}

export async function LoginReq(host, username) {
  return makeRequest(host + "?login", { classId: username });
}

export async function RaspGet(host, classId, day) {
  return makeRequest(host + "?req_client_schedule", {
    classId,
    day: apiFormatDate(day),
  });
}

export async function AdminReq(host, adminId) {
  return makeRequest(host + "?admin_login", { adminId });
}

export async function AdminUserFRequest(host, adminId) {
  return makeRequest(host + "?get_admin_user_f", { adminId });
}

export async function classUserFRequest(host, classId) {
  return makeRequest(host + "?get_class_user_f", { classId });
}

/**@param {{action:string,person?:string,value?}} data  */
export async function AdminUpdateRequest(host, adminId, data) {
  return makeRequest(host + "?update_admin", { adminId, ...data });
}
/**@param {{action:string,value?}} data  */
export async function ClassUpdateRequest(host, adminId, data) {
  return makeRequest(host + "?classprofile_edit", { adminId, ...data });
}
export async function getClassProfile(host, adminId) {
  return makeRequest(host + "?classprofile_view", { adminId });
}
