package Api

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

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

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

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

func getPostImageById(w http.ResponseWriter, r *http.Request) (Models.PostImage, error) {
	var (
		postImageData Models.PostImage
		id            string
		err           error
	)

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

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

	return postImageData, nil
}
