package minecraft_status

import (
	"go.uber.org/zap"
	"git.ssns.se/git/frozendragon/minecraft-ui/internal/rest"
	"net/http"
	"os/exec"
	"fmt"
)

type Resource struct {
	Logger *zap.Logger
}

type Request struct {
	Status bool `json:"status"`
}

type Response struct {
	Status bool `json:"status"`
}

func (r *Resource) Get(w http.ResponseWriter, req *http.Request) {
	out, _ := exec.Command("systemctl", "is-active", "minecraft").Output()

	//if err != nil {
	//	fmt.Println(err)
	//	w.WriteHeader(http.StatusInternalServerError)
	//	w.Write([]byte(err.Error()))
	//	return
	//}

	running := false

	if string(out) == "active" {
		running = true
	}

	response := &Response{
		Status: running,
	}
	rest.JSON(w, req, response)
}

func (r *Resource) Post(w http.ResponseWriter, req *http.Request) {
	var request Request
	if err := rest.DecodeJSON(req, &request); err != nil {
		fmt.Println(err)
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
		return
	}
	status := "stop"
	if request.Status {
		status = "start"
	}
	_, err := exec.Command("systemctl", status, "minecraft").Output()

	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
		return
	}
}