-- Copyright © 2014 Garrison Jensen
-- License
-- This code and text are dedicated to the public domain.
-- You can copy, modify, distribute and perform the work,
-- even for commercial purposes, all without asking permission.

import Parser
import Nock(Noun(Cell))
import Interpreter
import Optimizer
import System.Environment
import System.IO
import Data.List(intercalate)

interactiveNock :: IO ()
interactiveNock = do
            putStr "> "
            hFlush stdout
            nockStr <- getLine
            case nockStr of
                "quit" -> return ()
                _      -> do case parseString nockStr of
                                Just a -> print $ nock $ optimizer a
                                Nothing -> print "Invalid Nock expression."
                            >> interactiveNock

readNockFile :: String -> String -> IO ()
readNockFile file input = do
                  nockStr <- parseFile file
                  case parseString input of
                      Just a -> print $ nock $ optimizer $ Cell a nockStr
                      Nothing -> print $ nock $ optimizer nockStr

helpMsg :: String
helpMsg = "Usage: nock [-h] [file [input]]\n\
           \ If program file is not provided, \n\
           \ an interactive nock shell is started.\n\
           \ -h     Print help\n\
           \ Examples:\n\
           \    $ nock sub.nock [3 2]\n\
           \    1\n\
           \    $ nock\n\
           \    > [1 2 3 4]\n\
           \    4\n\
           \    > [43 [8 [1 0] 8 [1 6 [5 [0 7] 4 0 6] [0 6] 9 2 [0 2] [4 0 6] 0 7] 9 2 0 1]]\n\
           \    42\n\
           \    > quit\n"

main :: IO ()
main = do
    args <- getArgs
    case args of
        "-h":_ -> putStr helpMsg
        [] -> interactiveNock
        file:input -> readNockFile file $ intercalate " " input
