import test from 'ava';
import { User, Payment } from "../../lib/models.js";
import { base_host } from "../../lib/config.js";
import {sleep, random_user, expect, wait, tid, playstart, playstop} from '../../lib/testing.js';

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('standalone login page works', async (t) => {
  const {p} = t.context;
  const user = random_user();
  let payment = undefined;
  user.password_repeat = user.password;

  try {
    // using ... to copy the user since register modifies it
    let test1 = await User.register({...user});
    t.not(test1, undefined);
    t.not(test1.id, undefined);

    // we also have to craft a fake payment for them
    payment = await Payment.insert({
        user_id: test1.id,
        system: 'paypal',
        status: 'complete',
        internal_id: "fake-internal-id",
        sys_primary_id: "fake-primary-id",
        sys_secondary_id: "fake-secondary-id",
        sys_created_on: Date.now()
    });
    t.not(payment, undefined);
    t.not(payment.id, undefined);

    console.log("TEST", test1, "USER PASSWORD", user);
    user.id = test1.id; // save it for later deletes

    // login page loads
    await expect(t, p, tid('login-form'));

    // click login button and get errors
    await p.click(tid('login-button'));
    await expect(t, p, tid('email-error-0'));
    await expect(t, p, tid('password-error-0'));

    // fill out email, button has 1 error for password
    await p.fill('#email', test1.email);
    await p.click(tid('login-button'));
    await expect(t, p, tid('password-error-0'));
    // TODO: confirm the email errors are gone

    // give wrong password, one error at the top for invalid login
    await p.fill("#password", "asdfasdfsadf");
    await p.click(tid('login-button'));
    await expect(t, p, tid('login-error'));

    // fill out correct form, and redirect to watch
    await p.fill("#password", user.password);
    await p.click(tid('login-button'));
    await sleep(1000);
    await wait(p, tid('home-page'));

    // confirm home page and logout-link are visible
    await expect(t, p, tid('home-page'));
    await expect(t, p, tid('logout-link'));

    // logout and see login to chat
    await p.click(tid('logout-link'));

  } catch (error) {
    console.log(error);
    t.fail(error.message);
  } finally {
    if(user) await User.delete({id: user.id});
    if(payment) await Payment.delete({id: payment.id});
  }
});
