package libamuse

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

	"notabug.org/apiote/gott"
)

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

	return gott.Tuple(args), err
}

func renderWatchlist(args ...interface{}) interface{} {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	watchlist := result.result.(*datastructure.Watchlist)
	watchlist.Page = page
	watchlist.Query = request.id
	result.page = result.renderer.RenderWatchlist(*watchlist, result.languages)

	return gott.Tuple(args)
}

func ShowWatchlist(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(getWatchlist).
		Bind(getGenres).
		Bind(createRenderer).
		Map(renderWatchlist).
		Finish()

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