package libamuse

import (
	"notabug.org/apiote/amuse/accounts"
	"notabug.org/apiote/amuse/datastructure"
	"notabug.org/apiote/amuse/db"

	"notabug.org/apiote/gott"
)

func getTvQueue(args ...interface{}) (interface{}, error) {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	tvQueue, err := db.GetTvQueue(result.user.Username, request.id, page)
	result.result = &tvQueue

	return gott.Tuple(args), err
}

func renderTvQueue(args ...interface{}) interface{} {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	tvQueue := result.result.(*datastructure.TvQueue)
	tvQueue.Page = page
	tvQueue.Query = request.id
	result.page = result.renderer.RenderTvQueue(*tvQueue, result.languages)

	return gott.Tuple(args)
}

func ShowTvQueue(username string, auth accounts.Authentication, languages, mimetype, filter string, page int) (string, error) {
	auth.Necessary = true
	if page <= 0 {
		page = 1
	}
	request := &RequestData{id: filter, language: languages, mimetype: mimetype, auth: auth, username: username}
	r, err := gott.
		NewResult(gott.Tuple{request, &Result{}, page}).
		Bind(parseLanguage).
		Bind(verifyToken).
		Bind(verifyUser).
		Bind(getTvQueue).
		Bind(getGenres).
		Bind(createRenderer).
		Map(renderTvQueue).
		Finish()

	if err != nil {
		return "", err
	} else {
		return r.(gott.Tuple)[1].(*Result).page, nil
	}
}
