package webui

import (
	"fmt"
	"os"
	"strings"
	"time"
)

var taskSerialWriteLine = writeTaskSerialLine

func writeTaskSerialLine(line string) {
	line = strings.TrimSpace(line)
	if line == "" {
		return
	}
	payload := fmt.Sprintf("%s %s\n", time.Now().UTC().Format("2006-01-02 15:04:05Z"), line)
	for _, path := range []string{"/dev/ttyS0", "/dev/ttyS1", "/dev/console"} {
		f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
		if err != nil {
			continue
		}
		_, _ = f.WriteString(payload)
		_ = f.Close()
		return
	}
}

func taskSerialPrefix(t *Task) string {
	if t == nil {
		return "[task] "
	}
	return fmt.Sprintf("[task %s %s] ", t.ID, t.Name)
}

func taskSerialEvent(t *Task, event string) {
	if t == nil {
		return
	}
	taskSerialWriteLine(fmt.Sprintf("%s%s", taskSerialPrefix(t), strings.TrimSpace(event)))
}
