package api

import (
  "log"
  "time"

  "github.com/gofiber/fiber/v2"
  _ "github.com/mattn/go-sqlite3"
  sq "github.com/Masterminds/squirrel"
  "github.com/gofiber/fiber/v2/middleware/session"

  "MY/webapp/data"
  . "MY/webapp/common"
)

var STORE *session.Store


func GetApiStream(c *fiber.Ctx) error {
  sql, args, err := sq.Select("*").From("stream").ToSql()
  err = data.SelectJson[data.Stream](c, err, sql, args...)

  return IfErrNil(err, c)
}

func GetApiStreamId(c *fiber.Ctx) error {
  sql, args, err := sq.Select("*").
    From("stream").Where(sq.Eq{"id": c.Params("id")}).ToSql()

  err = data.GetJson[data.Stream](c, err, sql, args...)
  return IfErrNil(err, c)
}

func GetApiStreamIdLinks(c *fiber.Ctx) error {
  sql, args, err := sq.Select("*").
   From("stream_link").
   Where(sq.Eq{"stream_id": c.Params("id")}).ToSql()

  err = data.SelectJson[data.Link](c, err, sql, args...)

  return IfErrNil(err, c)
}

func PostApiLink(c *fiber.Ctx) error {
  var sql string
  var args []interface{}

  _, err := CheckAuthed(c, false)
  if err != nil { return c.Redirect("/login/") }

  link, err := ReceivePost[data.Link](c)
  if err != nil { return IfErrNil(err, c) }

  sql, args, err = sq.Insert("stream_link").
    Columns("stream_id", "url", "description").
    Values(link.StreamId, link.Url, link.Description).ToSql()

  _, err = data.Exec(err, sql, args...)
  if(err != nil) { return IfErrNil(err, c) }

  return c.Redirect("/live/")
}

func GetApiGame(c *fiber.Ctx) error {
  sql, args, err := sq.Select("*").From("game").ToSql()
  err = data.SelectJson[data.Game](c, err, sql, args...)

  return IfErrNil(err, c)
}

func GetApiGameId(c *fiber.Ctx) error {
  sql, args, err := sq.Select("*").
    From("game").Where(sq.Eq{"id": c.Params("id")}).ToSql()

  err = data.GetJson[data.Game](c, err, sql, args...)
  return IfErrNil(err, c)
}


func Setup(app *fiber.App) {
  STORE = session.New()

  app.Static("/", "./public", fiber.Static{
    Compress: false,
    CacheDuration: 1 * time.Nanosecond,
  })

  app.Get("/stream/:id/", Page("stream"))
  app.Get("/game/:id/:slug/", Page("game"))

  app.Get("/api/game", GetApiGame)
  app.Get("/api/game/:id", GetApiGameId)

  app.Get("/api/stream", GetApiStream)
  app.Get("/api/stream/:id", GetApiStreamId)
  app.Get("/api/stream/:id/links", GetApiStreamIdLinks)
  app.Post("/api/link", PostApiLink)

  // api/auth.go
  app.Get("/api/logout", GetApiLogout)
  app.Post("/api/register", PostApiRegister)
  app.Post("/api/login", PostApiLogin)
}

func Shutdown() {
  log.Println("Shutting down controllers...")
}
