package minecraft_status

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

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, err := exec.Command("systemctl", "status", "minecraft").Output()

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

	running := false

	if strings.Contains(string(out),"running") {
		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 {
		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
	}
}