package server

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

//StartService is exported
func (server *Handler) StartService(dir string) {
	if server.isRunning == false {
		//server.log = []Log{} //Clean up the log
		cmdName := "octave -i"
		fmt.Println(cmdName)
		cmdArgs := strings.Fields(cmdName)

		server.cmd = exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
		server.cmd.Dir = dir
		server.stdout, _ = server.cmd.StdoutPipe()
		server.stdin, _ = server.cmd.StdinPipe()
		server.cmd.Start()
		server.StartStdout()
		server.isRunning = true
		server.startCheckStatus()
		server.startLogAutoCleaning()
	} else {
		log.Println("Server is already running.")
	}
	//cmd.Wait()
	//init the server status checker

}

func (server *Handler) startCheckStatus() {
	go func() {
		server.cmd.Wait()
		log.Println("Stopped.")
		server.isRunning = false
	}()
}

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