package tests

import (
  "testing"
  "fmt"
  "reflect"
  "github.com/stretchr/testify/require"
  "MY/webapp/data"
  "MY/webapp/admin"
  sq "github.com/Masterminds/squirrel"
)

func TestAdminIndexPage(t *testing.T) {
  assert := require.New(t)
  models := data.Models()
  table := "user"
  model := models[table]

  fmt.Printf("\n------\ntable=%s; model=%s\n", table, model.Name())
  fields := reflect.VisibleFields(model)

  for _, field := range fields {
    fmt.Println("\t", field.Name, field.Type, field.Tag)
  }

  for i := 0; i < 87; i++ {
    val := reflect.New(model).Elem()
    email := fmt.Sprintf("test%d@test.com", i)
    val.FieldByName("Email").SetString(email)
    val.FieldByName("Username").SetString(fmt.Sprintf("zed%d", i))
    val.FieldByName("Password").SetString("garbage")

    sql_query, args, err := sq.Delete(table).Where(sq.Eq{"email": email}).ToSql()
    assert.NoError(err)

    _, err = data.DB.Exec(sql_query, args...)
    assert.NoError(err)

    id, count, err := admin.Insert(table, val)
    assert.Equal(count, 1)
    assert.NotEqual(id, 0)
    assert.NoError(err, email)
  }

  all_rows, err := admin.SelectTable(table, model, 20, 20 * 3)
  assert.NoError(err)

  for i, row := range all_rows { fmt.Println("row", i, row) }
  assert.Equal(20, len(all_rows))
  first_row := all_rows[0].(*data.User)

  result, err := admin.Get(table, model, int64(first_row.Id))
  if err != nil { fmt.Println("ERROR", err) }
  fmt.Println("TABLE: ", result)

  id := result.FieldByName("Id")
  result, err = admin.Get(table, model, id.Int())
  assert.NoError(err)

  fmt.Println("BEFORE: ", result)
  result.FieldByName("Username").SetString("joeblow")
  result.FieldByName("Email").SetString("what@what.com")
  fmt.Println("AFTER: ", result)

  err = admin.Update(table, result)
  assert.NoError(err, )

  err = admin.Delete(table, id.Int())
  assert.NoError(err)
}
