package Friends

import (
	"encoding/json"
	"net/http"
	"net/url"
	"strconv"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Api/Auth"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
)

// FriendRequestList gets friend request list
func FriendRequestList(w http.ResponseWriter, r *http.Request) {
	var (
		userSession Models.Session
		friends     []Models.FriendRequest
		values      url.Values
		returnJSON  []byte
		page        int
		err         error
	)

	values = r.URL.Query()

	page, err = strconv.Atoi(values.Get("page"))
	if err != nil {
		page = 0
	}

	userSession, _ = Auth.CheckCookie(r)

	friends, err = Database.GetFriendRequestsByUserID(userSession.UserID.String(), page)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	returnJSON, err = json.MarshalIndent(friends, "", "  ")
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write(returnJSON)
}
