package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"time"

	intcode "git.bullercodeworks.com/brian/adventofcode/2019/intcode-processor"
	helpers "git.bullercodeworks.com/brian/adventofcode/helpers"
)

func main() {
	progFileName := "input"
	if len(os.Args) > 1 {
		progFileName = os.Args[1]
	}
	dat, err := ioutil.ReadFile(progFileName)
	if err != nil {
		fmt.Println("Error reading program file:", err.Error())
		os.Exit(1)
	}
	var prog []int
	stringDat := strings.TrimSpace(string(dat))
	for _, v := range strings.Split(stringDat, ",") {
		prog = append(prog, helpers.Atoi(v))
	}
	fmt.Println("Day 5, part 1: Input '1'")
	fmt.Println("Day 5, part 2: Input '5'")
	p := intcode.NewProgram(prog)
	go func() {
		for {
			if st := p.State(); st != intcode.RET_OK {
				if st == intcode.RET_ERR {
					os.Exit(1)
				} else {
					os.Exit(0)
				}
			}
			if p.NeedsInput() {
				fmt.Print("Requesting Input: ")
				reader := bufio.NewReader(os.Stdin)
				inp, err := reader.ReadString('\n')
				if err != nil {
					fmt.Println("Input Error:", err.Error())
				} else {
					p.Input(helpers.Atoi(strings.TrimSpace(inp)))
				}
			}
			if p.NeedsOutput() {
				fmt.Println(p.Output())
			}
			switch p.State() {
			case intcode.RET_ERR:
				panic(p.Error())
			case intcode.RET_DONE:
				break
			}
			time.Sleep(1)
		}
	}()
	p.Run()
}