package libamuse

import (
	"notabug.org/apiote/amuse/accounts"
	"notabug.org/apiote/amuse/tmdb"

	"notabug.org/apiote/gott"
)

func getRandomTitle(args ...interface{}) (interface{}, error) {
	result := args[1].(*Result)
	languages := result.languages
	randomTitle, err := tmdb.GetRandomComedy(languages[0].String())
	result.result = randomTitle
	return gott.Tuple(args), err
}

func renderIndex(args ...interface{}) interface{} {
	result := args[1].(*Result)
	randomTitle := result.result.(string)
	result.page = result.renderer.RenderIndex(randomTitle, result.languages)
	return gott.Tuple(args)
}

func ShowIndex(language, mimetype string, authentication accounts.Authentication) (string, error) {
	authentication.Necessary = false
	r, err := gott.
		NewResult(gott.Tuple{&RequestData{language: language, mimetype: mimetype, auth: authentication}, &Result{}}).
		Bind(parseLanguage).
		Bind(verifyToken).
		Bind(getRandomTitle).
		Bind(createRenderer).
		Map(renderIndex).
		Finish()

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