package libamuse

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

	"notabug.org/apiote/gott"
)

func renderLogin(args ...interface{}) interface{} {
	result := args[1].(*Result)
	target := args[3].(string)
	var authError error
	if args[2] != nil {
		authError = args[2].(error)
	}
	result.page = result.renderer.RenderLogin(result.languages, authError, target)
	return gott.Tuple(args)
}

func ShowLogin(language, mimetype string, authErr *accounts.AuthError, target string) (string, error) {
	r, err := gott.
		NewResult(gott.Tuple{&RequestData{language: language, mimetype: mimetype}, &Result{}, authErr, target}).
		Bind(parseLanguage).
		Bind(createRenderer).
		Map(renderLogin).
		Finish()

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

func DoLogin(username, password, sfa string, remember bool) (string, error) {
	return accounts.Login(username, password, sfa, remember)
}

func renderLoggedOut(args ...interface{}) interface{} {
	result := args[1].(*Result)
	result.page = result.renderer.RenderLoggedOut(result.languages)
	return gott.Tuple(args)
}

func ShowLoggedOut(languages, mimetype string) (string, error) {
	r, err := gott.
		NewResult(gott.Tuple{&RequestData{language: languages, mimetype: mimetype}, &Result{}}).
		Bind(parseLanguage).
		Bind(createRenderer).
		Map(renderLoggedOut).
		Finish()

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