package Util

import (
	"errors"
	"log"
	"net/http"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"

	"github.com/gorilla/mux"
)

func GetUserId(r *http.Request) (string, error) {
	var (
		urlVars map[string]string
		id      string
		ok      bool
	)

	urlVars = mux.Vars(r)
	id, ok = urlVars["userID"]
	if !ok {
		return id, errors.New("Could not get id")
	}
	return id, nil
}

func GetUserById(w http.ResponseWriter, r *http.Request) (Models.User, error) {
	var (
		postData Models.User
		id       string
		err      error
	)

	id, err = GetUserId(r)
	if err != nil {
		log.Printf("Error encountered getting id\n")
		http.Error(w, "Error", http.StatusInternalServerError)
		return postData, err
	}

	postData, err = Database.GetUserById(id)
	if err != nil {
		log.Printf("Could not find user with id %s\n", id)
		http.Error(w, "Error", http.StatusInternalServerError)
		return postData, err
	}

	return postData, nil
}
