package Api

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

	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
	"github.com/gorilla/mux"
)

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

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

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

	id, err = getPostId(r)
	if err != nil {
		log.Printf("Error encountered getting id\n")
		JsonReturn(w, 500, "An error occured")
		return postData, err
	}

	postData, err = Database.GetPostById(id)
	if err != nil {
		log.Printf("Could not find pet with id %s\n", id)
		JsonReturn(w, 404, "Not found")
		return postData, err
	}

	return postData, nil
}
