import test from 'ava';
import {login, register_user, expect, tid, playstart, playstop} from '../../lib/testing.js';
import { User } from "../../lib/models.js";
import { base_host } from "../../lib/config.js";

const admin = `${base_host}/admin/#/table/`
test.before(async t => t.context = await playstart(`${base_host}/client/#/login`));

test.after(async t => {
  await playstop(t.context.browser, t.context.p);
});

test('test /admin tables works', async (t) => {
  const {p} = t.context;
  await expect(t, p, tid("page-login"));
  let user = await register_user(true);
  t.is(user.admin, true);
  t.not(user.email, undefined);
  user = await login(t, p, user);

  try {
    await p.goto(admin);
    await p.click(tid("sidebar-link-Tables"));
    await expect(t, p, tid("page-admin-tables"));

    await p.click(tid("table-name-user"));
    await p.click(tid("page-admin-table"));

    // search for nothing
    await p.fill("#search", "lkjalsdfjlasdfjlasdjflasdkjfasdfj");
    await p.press("#search", "Enter");
    await expect(t, p, tid("nothing-found"));

    // search for that user
    await p.fill("#search", user.email);
    await p.press("#search", "Enter");
    await expect(t, p, tid("row-0"));

    // clear the search
    await p.fill("#search", "");
    await p.press("#search", "Enter");

    await p.click(tid("row-1"));

    await expect(t, p, tid("page-admin-readupdate"));
    await expect(t, p, "#initials");
    await p.fill("#initials", "TTT");
    // click all the things
    await p.click(tid("button-copy"));
    await p.click(tid("button-update"));
    await p.click(tid("button-delete"));
    await p.click(tid("button-delete-no"));
    await p.click(tid("button-delete"));
    await p.click(tid("button-delete-yes"));

    await p.click(tid("link-create"));
    // just do a fail since that'll be alright
    await p.click(tid("button-create"));
    // and go back and done
    await p.click(tid("button-back"));
  } catch (error) {
    console.log(error);
    t.fail(error.message);
  } finally {
    if(user) await User.delete({id: user.id});
  }
});
