package libamuse

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

	"notabug.org/apiote/gott"

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

type queryData struct {
	query    string
	language string
	mimetype string
	page     string
}

func (d queryData) getLanguage() string {
	return d.language
}

func (d queryData) getMimeType() string {
	return d.mimetype
}

func doSearch(args ...interface{}) (interface{}, error) {
	data := args[0].(queryData)
	languages := args[2].([]language.Tag)
	tmdbResults, err := tmdb.Search(data.query, languages[0].String(), data.page)
	args[1] = tmdbResults
	return gott.Tuple(args), err
}

func renderQuery(args ...interface{}) interface{} {
	results := args[1].(*tmdb.SearchResults)
	renderer := args[3].(front.Renderer)
	languages := args[2].([]language.Tag)
	args[1] = renderer.RenderSearch(results, languages)
	return gott.Tuple(args)
}

func PerformSearch(query, language, mimetype, page string) (string, error) {
	result, err := gott.
		NewResult(gott.Tuple{queryData{query, language, mimetype, page}, nil, nil, nil}).
		Bind(parseLanguage).
		Bind(doSearch).
		Bind(createRenderer).
		Map(renderQuery).
		Finish()

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