package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	guuid "github.com/google/uuid"
)

var prevFileMD5 = ""

func SendCommand(w http.ResponseWriter, r *http.Request) {
	command, _ := mv(r, "command", false)
	MCServer.SendCommand(command)

	//Handle image output
	//generate UUID if for image

	id := guuid.New()
	filename := id.String() + ".png"
	MCServer.SendCommand("print -dpng " + filename)
	for {
		<-time.After(time.Second)
		fmt.Println("Waiting files...")
		if fileExists("./tmp/" + filename) {
			break
		}
	}
	if fileExists("./tmp/" + filename) {
		newFileMD5, _ := hashFileMD5("./tmp/" + filename)
		fmt.Println(newFileMD5)
		if newFileMD5 == prevFileMD5 && prevFileMD5 != "" {
			e := os.Remove("./tmp/" + filename)
			if e != nil {
				log.Fatal(e)
			}
		} else {
			if prevFileMD5 != "" {
				MCServer.AddLogEntry("<img style=\"width:400px;height:auto\" src=\"./output/" + filename + "\"></img>")
			} else {
				e := os.Remove("./tmp/" + filename)
				if e != nil {
					log.Fatal(e)
				}
			}
		}
		prevFileMD5 = newFileMD5
	}

	//end image output
	sendJSONResponse(w, "OK")
}

func hashFileMD5(filePath string) (string, error) {
	var returnMD5String string
	file, err := os.Open(filePath)
	if err != nil {
		return returnMD5String, err
	}
	defer file.Close()
	hash := md5.New()
	if _, err := io.Copy(hash, file); err != nil {
		return returnMD5String, err
	}
	hashInBytes := hash.Sum(nil)[:16]
	returnMD5String = hex.EncodeToString(hashInBytes)
	return returnMD5String, nil
}
