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

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

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

test('test /profile works', async (t) => {
  const {p} = t.context;
  const test_password = "newtestpassword";

  try {
    const user = await register_user(true);
    await login(t, p, user);
    await expect(t, p, tid("user-profile-button"));
    await p.click(tid("user-profile-button"));
    // confirm we get errors
    await expect(t, p, tid("page-user-profile"));

    // change the user's password, but fail
    await p.fill("#password", test_password);
    await p.click(tid("update-button"));

    await expect(t, p, tid("password_repeat-error-0"));

    // change the user's password for real
    await p.fill("#password_repeat", test_password);
    await p.click(tid("update-button"));

    // should work now
    const notice = await expect(t, p, tid("update-notice"));
    t.is(notice, "User profile updated.");

    await p.click(tid("logout-link"));

    // attempt a login with the new password
    user.raw_password = test_password;
    await login(t, p, user);

    // then try going back
    await expect(t, p, tid("user-profile-button"));
    await p.click(tid("user-profile-button"));

  } catch (error) {
    console.log(error);
    t.fail(error.message);
  }
});
