package tests

import (
    "testing"
    "context"
    "log"
    "time"
    "github.com/stretchr/testify/assert"
    browser "github.com/chromedp/chromedp"
)

func Run(assert *assert.Assertions, ctx context.Context, actions ...browser.Action) {
    err := browser.Run(ctx, actions...)
    assert.NoError(err)
}

func Setup(timeout time.Duration) (context.Context, context.CancelFunc) {
    opts := append(browser.DefaultExecAllocatorOptions[:],
                    browser.Flag("headless", true),)

    ctx, cancel := browser.NewExecAllocator(context.Background(), opts...)

    ctx, _ = browser.NewContext(ctx, browser.WithLogf(log.Printf))

    ctx, _ = context.WithTimeout(ctx, timeout * time.Second)

    return ctx, cancel
}

/*
func TestLogin(t *testing.T) {
    assert := assert.New(t)

    ctx, cancel := Setup(5); defer cancel()

    Run(assert, ctx,
    browser.Navigate(`http://127.0.0.1:5002/login/`),
    browser.WaitVisible(`body > footer`),
    browser.WaitVisible(`[data-testid="login-page"]`),
    browser.SendKeys(`#username`, `zedshaw`),
    browser.SendKeys(`#password`, `1234`),
    browser.Click(`#login-submit`, browser.NodeVisible),
    browser.WaitVisible(`body > footer`),
    browser.WaitVisible(`[data-testid="home-page"]`))
}
*/

func TestStreamPage(t *testing.T) {
    assert := assert.New(t)

    ctx, cancel := Setup(2);
    defer cancel();

    var example string

    err := browser.Run(ctx,
      browser.Navigate(`http://127.0.0.1:5002`),
      browser.WaitVisible(`body > footer`),
      browser.WaitVisible(`#streams`),
    )
    assert.NoError(err)

    resp, err := browser.RunResponse(ctx, browser.Click(`#streams`, browser.ByID))
    assert.Equal(resp.Status, int64(200))
    assert.NoError(err)

    err = browser.Run(ctx, browser.WaitVisible(`#streams-title`))
    assert.NoError(err)

    err = browser.Run(ctx, browser.Text(`#streams-title`, &example))
    assert.NoError(err)

    assert.Equal(example, "Past Streams")
}