import type { Page } from "playwright";

interface credentials {
  username: string;
  password: string;
}

async function whoAmI({ page }: {
  page: Page;
}): Promise<string> {
  if (await isLogOut({ page })) return "";
  return (await page.locator('.login_block_user a[data-toggle="dropdown"]')
    .textContent())?.trim() || "";
}

async function isLogOut({ page }: {
  page: Page;
}): Promise<boolean> {
  return (
    await page.locator(".login_block").count() === 0 &&
    await page.locator(".login_table").count() > 0
  );
}

async function doLogout({ page }: {
  page: Page;
}): Promise<void> {
  if (await isLogOut({ page })) return;
  await page.locator(".login_block .dropdown").click();
  await page.locator("i.fa-sign-out-alt").click();
}

async function doLogin(
  { page, dolibarrAddress }: {
    page: Page;
    dolibarrAddress: string;
  },
  { username, password }: credentials,
): Promise<void> {
  await page.goto(`${dolibarrAddress}/`);

  if (await whoAmI({ page }) === username) return;
  await doLogout({ page });

  await page.fill('input[name="username"]', username);
  await page.fill('input[name="password"]', password);
  await page.click('input[type="submit"]');
}

async function doAdminLogin({ page, dolibarrAddress, adminCredentials }: {
  page: Page;
  dolibarrAddress: string;
  adminCredentials: credentials;
}) {
  await doLogin({ page, dolibarrAddress }, adminCredentials);
}

export default {
  doAdminLogin,
  doLogin,
  doLogout,
  isLogOut,
  whoAmI,
};
