package Api

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"

	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Util"
	"github.com/gofrs/uuid"
)

func createPostImage(w http.ResponseWriter, r *http.Request) {
	var (
		postData    Models.Post
		postID      string
		postUUID    uuid.UUID
		postImage   Models.PostImage
		formData    *multipart.Form
		fileHeaders []*multipart.FileHeader
		fileHeader  *multipart.FileHeader
		file        multipart.File
		fileBytes   []byte
		fileObject  Util.FileObject
		returnJson  []byte
		err         error
	)

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

	postUUID = uuid.FromStringOrNil(postID)

	// TODO: Change arg to bitwise op
	err = r.ParseMultipartForm(200000)
	if err != nil {
		log.Printf("Error encountered parsing multipart form: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	formData = r.MultipartForm

	fileHeaders = formData.File["files"]

	for _, fileHeader = range fileHeaders {
		file, err = fileHeader.Open()
		if err != nil {
			log.Printf("Error encountered while post image upload: %s\n", err.Error())
			JsonReturn(w, 500, "An error occured")
			return
		}
		defer file.Close()

		fileBytes, err = ioutil.ReadAll(file)
		if err != nil {
			log.Printf("Error encountered while post image upload: %s\n", err.Error())
			JsonReturn(w, 500, "An error occured")
			return
		}

		fileObject, err = Util.WriteFile(fileBytes, "image")
		if err != nil {
			log.Printf("Error encountered while post image upload: %s\n", err.Error())
			JsonReturn(w, 415, "Invalid filetype")
			return
		}

		postImage = Models.PostImage{
			PostID:   postUUID,
			Filepath: fileObject.Filepath,
			Mimetype: fileObject.Mimetype,
			Size:     fileObject.Size,
		}

		err = Database.CreatePostImage(&postImage)
		if err != nil {
			log.Printf("Error encountered while creating post_image record: %s\n", err.Error())
			JsonReturn(w, 500, "An error occured")
			return
		}
	}

	postData, err = getPostById(w, r)
	if err != nil {
		return
	}

	returnJson, err = json.MarshalIndent(postData, "", "  ")
	if err != nil {
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJson)
}

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

	postImageData, err = getPostImageById(w, r)
	if err != nil {
		return
	}

	err = Database.DeletePostImage(&postImageData)
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
}
