package libamuse

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

	"notabug.org/apiote/gott"

	"golang.org/x/text/language"
	"strconv"
)

func getFilm(args ...interface{}) (interface{}, error) {
	data := args[0].(requestData)
	languages := args[2].([]language.Tag)
	tmdbFilm, err := tmdb.GetFilm(data.id, languages[0].String(), data.etag)
	args[1] = tmdbFilm
	return gott.Tuple(args), err
}

func getCollection(args ...interface{}) (interface{}, error) {
	tmdbFilm := args[1].(*tmdb.Film)
	languages := args[2].([]language.Tag)
	var err error
	if tmdbFilm.Collection.Id != 0 {
		tmdbCollection, e := tmdb.GetCollection(
			strconv.FormatInt(int64(tmdbFilm.Collection.Id), 10),
			languages[0].String(),
			"")
		tmdbFilm.Collection = *tmdbCollection
		err = e
	}
	return gott.Tuple(args), err
}

func renderFilm(args ...interface{}) (interface{}) {
	film := args[1].(*tmdb.Film)
	languages := args[2].([]language.Tag)
	renderer := args[3].(front.Renderer)
	args[1] = renderer.RenderFilm(film, languages)
	return gott.Tuple(args)
}

func ShowFilm(id string, etag string, language string, mimetype string) (string, error) {
	result, err := gott.
		NewResult(gott.Tuple{requestData{id, etag, language, mimetype}, nil, nil, nil}).
		Bind(parseLanguage).
		Bind(getFilm).
		Bind(getCollection).
		Bind(createRenderer).
		Map(renderFilm).
		Finish()

	if err != nil {
		return "", err
	} else {
		return result.(gott.Tuple)[1].(string), nil
	}

}
