package libamuse

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

	"strings"

	"notabug.org/apiote/gott"
)

func getBookSerie(args ...interface{}) (interface{}, error) {
	data := args[0].(*RequestData)
	result := args[1].(*Result)
	languages := result.languages
	bookSerie, err := wikidata.GetBookSerie(data.id, languages[0].String(), data.connection)
	result.result = bookSerie
	return gott.Tuple(args), err
}

func getOrdinals(args ...interface{}) (interface{}, error) {
	data := args[0].(*RequestData)
	result := args[1].(*Result)
	bookSerie := result.result.(*wikidata.BookSerie)
	_, err := wikidata.GetBookSerieOrdinals(data.id, bookSerie, data.connection)
	return gott.Tuple(args), err
}

func getCovers(args ...interface{}) (interface{}, error) {
	data := args[0].(*RequestData)
	result := args[1].(*Result)
	bookSerie := result.result.(*wikidata.BookSerie)
	languages := result.languages

	for i, part := range bookSerie.SortedParts {
		partId := strings.Replace(part.Uri, "/books/", "", 1)
		cover, err := wikidata.GetCover(partId, languages[0].String(), data.connection)
		if err != nil {
			return gott.Tuple(args), err
		}
		bookSerie.SortedParts[i].Cover = cover
	}
	return gott.Tuple(args), nil
}

func renderBookSerie(args ...interface{}) interface{} {
	result := args[1].(*Result)
	bookSerie := result.result.(*wikidata.BookSerie)
	result.page = result.renderer.RenderBookSerie(*bookSerie, result.languages)
	return gott.Tuple(args)
}

func ShowBookSerie(id, language, mimetype string, auth accounts.Authentication) (string, error) {
	auth.Necessary = false
	r, err := gott.
		NewResult(gott.Tuple{&RequestData{id: id, language: language, mimetype: mimetype, auth: auth}, &Result{}}).
		Bind(parseLanguage).
		Bind(verifyToken).
		Bind(getBookSerie).
		Bind(getOrdinals).
		Bind(getDescription).
		Bind(getCovers).
		Bind(createRenderer).
		Map(renderBookSerie).
		Finish()

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