package Messages

import (
	"encoding/base64"
	"encoding/json"
	"net/http"

	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Database"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Models"
	"git.tovijaeschke.xyz/tovi/Capsule/Backend/Util"
	"github.com/gorilla/mux"
)

// AddConversationImage adds an image for a conversation icon
func AddConversationImage(w http.ResponseWriter, r *http.Request) {
	var (
		attachment         Models.Attachment
		conversationDetail Models.ConversationDetail
		urlVars            map[string]string
		detailID           string
		decodedFile        []byte
		fileName           string
		ok                 bool
		err                error
	)

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

	conversationDetail, err = Database.GetConversationDetailByID(detailID)
	if err != nil {
		http.Error(w, "Not Found", http.StatusNotFound)
		return
	}

	err = json.NewDecoder(r.Body).Decode(&attachment)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	if attachment.Data == "" {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	decodedFile, err = base64.StdEncoding.DecodeString(attachment.Data)
	fileName, err = Util.WriteFile(decodedFile)
	attachment.FilePath = fileName

	conversationDetail.Attachment = attachment

	err = Database.UpdateConversationDetail(&conversationDetail)
	if err != nil {
		http.Error(w, "Error", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
