package main

import (
	"fmt"
	"os"
	"time"

	"golang.org/x/term"
)

func main() {
	ctrl := newEvacuationController("../eeprom/Vac-ours FK-U12.bin")

	// Switch stdin into 'raw' mode.
	oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer term.Restore(int(os.Stdin.Fd()), oldState)

	// Keyboard input channel, byte at a time.
	kbdC := make(chan byte)
	go func() {
		for {
			b := make([]byte, 1)
			_, err = os.Stdin.Read(b)
			if err == nil {
				kbdC <- b[0]
			}
		}
	}()

	t := time.Now()

	// Countdown timers for simulating a button press.
	pumpdownButton := time.Duration(0)
	ventButton := time.Duration(0)

	lastPrint := time.Now()

	fmt.Print("\033[H\033[2J")
	for {
		dt := time.Since(t)
		t = time.Now()
		if !ctrl.step(dt) {
			break
		}

		select {
		case b := <-kbdC:
			switch b {
			case 'p':
				pumpdownButton = time.Millisecond * 1000
			case 'v':
				ventButton = time.Millisecond * 1000
			case 'q':
				return
			}
		default:
		}

		ctrl.pressPumpdown(pumpdownButton > 0)
		if pumpdownButton > 0 {
			pumpdownButton -= dt
		}
		ctrl.pressVent(ventButton > 0)
		if ventButton > 0 {
			ventButton -= dt
		}

		if time.Since(lastPrint) > time.Millisecond*10 {
			lastPrint = time.Now()
			fmt.Print("\033[1;1H")
			fmt.Printf("Controls: [v] vent, [p] pumpdown, [q] quit\r\n")
			fmt.Printf("PC %04x\r\n", ctrl.lastIOPC)
			fmt.Printf("%s\r\n", ctrl.getIndcators().String())
			fmt.Printf("%s %s\r\n", ctrl.m1.status("M1"), ctrl.m2.status("M2"))
			fmt.Printf("%s %s\r\n", ctrl.m1.barrier.status(), ctrl.m2.barrier.status())
			fmt.Print("\r\n")
		}
	}
}