import test from 'ava';
import {register_user, sleep, expect, tid, playstart, playstop} from '../../lib/testing.js';
import { Livestream } from "../../lib/models.js";

const fixture = {
    "title": "ALPHA Early Access Release Party",
    "description": "Come hang out and watch me survive the first release of Learn JS the Hard Way.",
    "starts_on": "2022-04-15 14:00:00-04",
    "is_free": 0,
    "state": "pending",
    "viewer_count": 206,
    "episode": 1
};

test.before(async t => {
  t.context = await playstart('http://127.0.0.1:5001/client/#/live/')

  const count = await Livestream.count({state: "pending"});

  if(count <= 0) {
    for(let state of ["pending", "finished", "ready"]) {
      fixture.title = `Test of a ${state} livestream.`;
      fixture.state = state;
      delete fixture.id;
      await Livestream.insert(fixture);
    }
  }
});

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

test('test pending livestream works', async (t) => {
  const {browser, context, p} = t.context;
  const user = await register_user();
  const pending = await Livestream.first({state: "pending"});
  t.not(pending, undefined);

  try {
    await expect(t, p, tid("streams-page"));
    await expect(t, p, tid(`stream-link-${pending.id}`));
    await p.click(tid(`stream-link-${pending.id}`));
    await expect(t, p, tid("live-page"));

    // confirm that pending stream has start message

    const message = await expect(t, p, tid("pending-message"));
    t.regex(message, /^This live stream.*/, "Pending message not found.");
  } catch (error) {
    console.log(error);
    t.fail(error.message);
  }
});
