package libamuse

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

	"notabug.org/apiote/gott"

	"time"
)

func getExperiences(args ...interface{}) (interface{}, error) {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	experiences, err := db.GetUserExperiences(result.user.Username, request.id, page)
	result.result = experiences

	return gott.Tuple(args), err
}

func parseExperienceDates(args ...interface{}) interface{} {
	result := args[1].(*Result)
	experiences := result.result.(datastructure.Experiences)
	location, _ := time.LoadLocation(result.user.Timezone)
	for i, experience := range experiences.List {
		experience.Datetime = experience.Datetime.In(location)
		experiences.List[i] = experience
	}
	result.result = experiences

	return gott.Tuple(args)
}

func renderExperiences(args ...interface{}) interface{} {
	request := args[0].(*RequestData)
	result := args[1].(*Result)
	page := args[2].(int)
	experiences := result.result.(datastructure.Experiences)
	experiences.Page = page
	experiences.Query = request.id
	result.page = result.renderer.RenderExperiences(experiences, result.languages)

	return gott.Tuple(args)
}

func ShowExperiences(username string, auth accounts.Authentication, languages, mimetype, filter string, page int) (string, error) {
	auth.Necessary = true
	if page <= 0 {
		page = 1
	}

	request := &RequestData{id: filter, language: languages, mimetype: mimetype, auth: auth, username: username}
	r, err := gott.
		NewResult(gott.Tuple{request, &Result{}, page}).
		Bind(parseLanguage).
		Bind(verifyToken).
		Bind(verifyUser).
		Bind(getExperiences).
		Map(parseExperienceDates).
		Bind(createRenderer).
		Map(renderExperiences).
		Finish()

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