package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	defaultState := *NewExecutionState()
	defaultState.Environment["SHELL"] = "gash"
	defaultState.Descriptors[DESCRIPTOR_STDIN] = os.Stdin
	defaultState.Descriptors[DESCRIPTOR_STDOUT] = os.Stdout
	defaultState.Descriptors[DESCRIPTOR_STDERR] = os.Stderr

	sc := bufio.NewScanner(os.Stdin)
	tokBuff := make([]Token, 0)

	for {

		if len(tokBuff) > 0 {
			fmt.Printf("... ")
		} else {
			fmt.Printf("$ ")
		}

		// Read line
		if !sc.Scan() {
			break
		}
		if len(sc.Text()) > 0 && sc.Text()[0] == '\x04' {
			break // ctrl+d
		}

		// Tokenize
		readTokens := tokenize(sc.Text())
		tokBuff = append(tokBuff, readTokens...)

		// Parse as many statements as possible
		for len(tokBuff) > 0 {

			remainder, stmt, err := TryParseFrom(tokBuff)

			//fmt.Printf("Parse %v :: %v :: %v\n", remainder, stmt, err)

			if err != nil {
				fmt.Fprintf(os.Stdout, "Error: %s\n")
				tokBuff = make([]Token, 0) // clear
				break
			}

			if stmt != nil {
				res := stmt.Execute(&defaultState)

				// Store exitcode in $?
				defaultState.Variables["?"] = fmt.Sprintf("%d", res.ExitCode)
			}

			tokBuff = remainder // continue parsing
		}
	}
}
