package server

import (
	"bufio"
	"fmt"
	"os/exec"
	"strings"
	"time"
)

//StartService is exported
func (server *Handler) StartService() {
	cmdName := server.JavaPath + " -Xmx" + server.maxRAM + " -Xms" + server.minRAM + " -jar " + server.ServerJar + " nogui " + server.args
	fmt.Println(cmdName)
	cmdArgs := strings.Fields(cmdName)

	cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
	cmd.Dir = "./server/"
	server.stdout, _ = cmd.StdoutPipe()
	server.stdin, _ = cmd.StdinPipe()
	cmd.Start()

	server.StartStdout()
	//cmd.Wait()
}

//StartStdout is exported
func (server *Handler) StartStdout() {
	i := 0
	buf := bufio.NewReader(server.stdout)
	go func() {
		for {
			line, _, _ := buf.ReadLine()
			if string(line) != "" {
				newLog := Log{
					ID:        i,
					Timestamp: time.Now(),
					Log:       string(line),
				}
				server.log = append(server.log, newLog)
				i++
			}
		}
	}()
}
