package libamuse

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

	"notabug.org/apiote/gott"

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

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

func getSeasons(args ...interface{}) (interface{}, error) {
	serie := args[1].(*tmdb.Serie)
	languages := args[2].([]language.Tag)
	seasons, err := tmdb.GetSeasons(serie, languages[0].String(), "")
	serie.Seasons = seasons
	args[1] = serie
	return gott.Tuple(args), err
}

func renderSerie(args ...interface{}) interface{} {
	serie := args[1].(*tmdb.Serie)
	languages := args[2].([]language.Tag)
	renderer := args[3].(front.Renderer)
	args[1] = renderer.RenderSerie(serie, languages)
	return gott.Tuple(args)
}

func ShowSerie(id, etag, languages, mimetype string) (string, error) {
	result, err := gott.
		NewResult(gott.Tuple{requestData{id, etag, languages, mimetype}, nil, nil, nil}).
		Bind(parseLanguage).
		Bind(getSerie).
		Bind(getSeasons).
		Bind(createRenderer).
		Map(renderSerie).
		Finish()

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