import { readFile, access, readdir } from "fs/promises";
import path from "path";

import matter from "gray-matter";
// import { Client } from "ldapts";
import { serialize } from "next-mdx-remote/serialize";

import { capitalize } from "@/utils";
// import { getCurrentTermYear, getTermYear, TermYear } from "@/utils"; // needed if re-enabling LDAP

const EXECS_PATH = path.join("content", "team", "execs");
const FILETYPE = ".md";

const execPositions: { [position: string]: string } = {
  president: "President",
  "vice-president": "Vice-President",
  secretary: "Assistant Vice-President",
  treasurer: "Treasurer",
  sysadmin: "Systems Administrator",
};

const orderedExecPositions: string[] = [
  "president",
  "vice-president",
  "secretary",
  "treasurer",
  "sysadmin",
];

export interface Metadata {
  name: string;
  role?: string;
  image: string;
}
interface Person {
  firstName: string;
  lastName: string;
}

interface Exec {
  person: Person;
  position: string;
}

export async function getExecs() {
  const execs = await getExecNamePosPairs();

  return await Promise.all(execs.map(getExec));
}

async function getExec(exec: Exec) {
  let content, metadata;
  const expectedFileName =
    `${exec.person.firstName}` +
    (exec.person.lastName ? `-${exec.person.lastName}` : "");

  try {
    const raw = await readFile(
      path.join(EXECS_PATH, `${expectedFileName}${FILETYPE}`)
    );
    ({ content, data: metadata } = matter(raw));

    const image = await getMemberImagePath(metadata.name as string);

    return {
      content: await serialize(content),
      metadata: { ...metadata, image } as Metadata,
    };
  } catch (err) {
    // Capitalize the first letter of the first name and last name
    const firstName = capitalize(exec.person.firstName);
    const lastName = capitalize(exec.person.lastName);

    const posName = execPositions[exec.position];
    content = "Coming Soon!";
    metadata = {
      name: `${firstName} ${lastName}`,
      role: `${posName}`,
    };

    const image = await getMemberImagePath(metadata.name);

    return {
      content: await serialize(content),
      metadata: { ...metadata, image } as Metadata,
    };
  }
}

async function getExecNamePosPairs(): Promise<Exec[]> {
  const CodeyExec = {
    person: { firstName: "codey", lastName: "" },
    position: "mascot",
  };

  // LDAP disabled: always use local files
  const fromFiles = await getExecsFromFiles();
  /*
  // LDAP implementation (disabled)
  const url = "ldap://ldap1.csclub.uwaterloo.ca";
  const searchDN = "ou=People,dc=csclub,dc=uwaterloo,dc=ca";
  const client = new Client({ url });

  // position: name
  const execMembers: { [position: string]: string } = {};

  let formattedExec: Exec[] = [];

  try {
    await client.bind("", "");

    const terms: TermYear[] = [];

    // check members from last two terms (including current term)
    for (const termYear of getTermYear(getCurrentTermYear(), {
      goBackwards: true,
    })) {
      if (terms.length >= 2) {
        break;
      }
      terms.push(termYear);
    }

    const termsFilters = terms
      .map(
        ({ term, year }: TermYear) =>
          `(term=${(term as string).slice(0, 1)}${year})`
      )
      .join("");

    const { searchEntries } = await client.search(searchDN, {
      scope: "sub",
      filter: `(&(objectClass=member)(|${termsFilters}))`,
    });

    // item.position might be an array if the member has more than one position
    searchEntries.forEach((item) => {
      if (typeof item.position === "string" && item.position in execPositions) {
        execMembers[item.position] = item.cn as string;
      } else if (item.position instanceof Array) {
        item.position.forEach((p) => {
          if ((p as string) in execPositions) {
            execMembers[p as string] = item.cn as string;
          }
        });
      }
    });

    formattedExec = orderedExecPositions
      .map((position) => {
        const fullName = execMembers[position];
        if (fullName == undefined) {
          return null;
        }
        const nameParts = fullName.split(" ");
        const firstName = nameParts[0].toLowerCase();
        const lastName =
          nameParts.length > 1
            ? nameParts[nameParts.length - 1].toLowerCase()
            : "";
        return {
          person: { firstName: firstName, lastName: lastName },
          position: position,
        };
      })
      .filter((pair) => pair != null) as Exec[];

    formattedExec = [...formattedExec, CodeyExec];
  } finally {
    await client.unbind();
  }

  return formattedExec;
  */
  return [...fromFiles, CodeyExec];
}

// execs from local markdown files
async function getExecsFromFiles(): Promise<Exec[]> {
  const files = await readdir(EXECS_PATH);

  const execByPosition: { [position: string]: Exec } = {};

  for (const file of files) {
    if (!file.endsWith(FILETYPE)) continue;
    const base = file.slice(0, -FILETYPE.length);
    if (base.toLowerCase() === "codey") continue;

    try {
      const raw = await readFile(path.join(EXECS_PATH, file), "utf-8");
      const { data } = matter(raw);
      const role = (data?.role ?? "") as string;

      const position = Object.entries(execPositions).find(
        ([, v]) => v === role
      )?.[0];
      if (!position) continue;

      const nameParts = base.split("-");
      const firstName = (nameParts[0] ?? "").toLowerCase();
      const lastName = (nameParts.slice(1).join("-") ?? "").toLowerCase();

      execByPosition[position] = {
        person: { firstName, lastName },
        position,
      };
    } catch {
      // ignore bad files
    }
  }

  return orderedExecPositions
    .map((pos) => execByPosition[pos])
    .filter((x) => x != null);
}

async function getImage(imgPath: string) {
  try {
    await access(path.join("public", imgPath));
    return imgPath;
  } catch {
    return undefined;
  }
}

export async function getMemberImagePath(name: string) {
  const imgPath = path.join("images", "team", name.replace(/\s/g, ""));

  const img =
    (await getImage(imgPath + ".jpg")) ??
    (await getImage(imgPath + ".png")) ??
    (await getImage(imgPath + ".gif")) ??
    (await getImage(imgPath + ".jpeg")) ??
    (await getImage(imgPath + ".JPG")) ??
    (await getImage(imgPath + ".PNG")) ??
    (await getImage(imgPath + ".GIF")) ??
    (await getImage(imgPath + ".JPEG")) ??
    (await getMemberPlaceholderImage(name));

  return img;
}

const getMemberPlaceholderImage = (() => {
  const placeholders: string[] = [];
  async function getPlaceholders() {
    const placeholderDirectory = path.join("images", "team", "placeholders");

    const placeholders = (await readdir(placeholderDirectory)).map((filename) =>
      path.join(placeholderDirectory, filename)
    );

    const supportedExts = [".jpg", ".png", ".jpeg", ".gif"];

    return placeholders.filter((file) =>
      supportedExts.includes(path.extname(file).toLowerCase())
    );
  }

  return async (name: string) => {
    if (placeholders.length === 0) {
      placeholders.push(...(await getPlaceholders()));
    }

    const sum = name
      .split("")
      .map((char) => char.charCodeAt(0))
      .reduce((a, b) => a + b, 0);

    const index = sum % placeholders.length;

    return placeholders[index];
  };
})();
