package friend

import (
	"net/http"

	"code.nonshy.com/nonshy/website/pkg/config"
	"code.nonshy.com/nonshy/website/pkg/log"
	"code.nonshy.com/nonshy/website/pkg/models"
	"code.nonshy.com/nonshy/website/pkg/session"
	"code.nonshy.com/nonshy/website/pkg/templates"
)

// Friends list and pending friend request endpoint.
func Friends() http.HandlerFunc {
	tmpl := templates.Must("friend/friends.html")
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var (
			view       = r.FormValue("view")
			isRequests = view == "requests"
			isPending  = view == "pending"
			isIgnored  = view == "ignored"
		)

		currentUser, err := session.CurrentUser(r)
		if err != nil {
			session.FlashError(w, r, "Unexpected error: could not get currentUser.")
			templates.Redirect(w, "/")
			return
		}

		// Get our friends.
		pager := &models.Pagination{
			PerPage: config.PageSizeFriends,
			Sort:    "updated_at desc",
		}
		pager.ParsePage(r)
		friends, err := models.PaginateFriends(currentUser, isRequests, isPending, isIgnored, pager)
		if err != nil {
			session.FlashError(w, r, "Couldn't paginate friends: %s", err)
			templates.Redirect(w, "/")
			return
		}

		// Inject relationship booleans.
		models.SetUserRelationships(currentUser, friends)

		// Ignored friend request count.
		ignoredFriendCount, err := models.CountIgnoredFriendRequests(currentUser.ID)
		if err != nil {
			log.Error("Ignored Friend Request Count (%s): %s", currentUser.Username, err)
		}

		var vars = map[string]interface{}{
			"IsRequests":         isRequests,
			"IsPending":          isPending,
			"IsIgnored":          isIgnored,
			"Friends":            friends,
			"IgnoredFriendCount": ignoredFriendCount,
			"Pager":              pager,
		}
		if err := tmpl.Execute(w, r, vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	})
}
