package libamuse

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

	"notabug.org/apiote/gott"

	"strconv"
)

type QueryData struct {
	query    string
	language string
	mimetype string
	page     string
	auth     accounts.Authentication
	username string
}

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

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

func (d QueryData) getAuth() accounts.Authentication {
	return d.auth
}

func (d QueryData) getReqUsername() string {
	return d.username
}

func searchTmdb(args ...interface{}) (interface{}, error) {
	data := args[0].(*QueryData)
	result := args[1].(*Result)
	languages := result.languages
	results, err := tmdb.Search(data.query, languages[0].String(), data.page)
	result.result = results
	return gott.Tuple(args), err
}

func searchInventaire(args ...interface{}) (interface{}, error) {
	data := args[0].(*QueryData)
	result := args[1].(*Result)
	languages := result.languages
	page, _ := strconv.ParseInt(data.page, 10, 64)
	results, err := wikidata.Search(data.query, languages[0].String(), page)
	result.result2 = results
	return gott.Tuple(args), err
}

func renderQuery(args ...interface{}) interface{} {
	result := args[1].(*Result)
	tmdbResults := result.result.(*tmdb.SearchResults)
	inventaireResults := result.result2.(*wikidata.SearchResults)
	result.page = result.renderer.RenderSearch(tmdbResults, inventaireResults, result.languages)
	return gott.Tuple(args)
}

func PerformSearch(query, language, mimetype, page string, auth accounts.Authentication) (string, error) {
	auth.Necessary = false
	r, err := gott.
		NewResult(gott.Tuple{&QueryData{query: query, language: language, mimetype: mimetype, page: page, auth: auth}, &Result{}}).
		Bind(parseLanguage).
		Bind(verifyToken).
		Bind(searchTmdb).
		Bind(searchInventaire).
		Bind(createRenderer).
		Map(renderQuery).
		Finish()

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