package Messages

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

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

	"github.com/gorilla/mux"
)

// Messages gets messages by the associationKey
func Messages(w http.ResponseWriter, r *http.Request) {
	var (
		messages       []Models.Message
		message        Models.Message
		urlVars        map[string]string
		associationKey string
		values         url.Values
		returnJSON     []byte
		page           int
		i              int
		ok             bool
		err            error
	)

	urlVars = mux.Vars(r)
	associationKey, ok = urlVars["associationKey"]
	if !ok {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	values = r.URL.Query()

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

	messages, err = Database.GetMessagesByAssociationKey(associationKey, page)
	if !ok {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	for i, message = range messages {
		if message.MessageData.AttachmentID == nil {
			continue
		}

		messages[i].MessageData.Attachment.ImageLink = message.MessageData.Attachment.FilePath
	}

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

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