{-
  Main
-}

module Main where

import Utils
import Schema
import Query

import System.IO
import System.Exit
import qualified Data.Map as M

runQuery :: Schema -> String -> IO ()
runQuery schema queryString = do
  query <- (getQuery schema queryString)
  evalQuery query

printHelp :: IO ()
printHelp = do
  putStrLn "Commands:"
  putStrLn ":h               | Display this help"
  putStrLn ":s               | Print details about the schema"
  putStrLn ":t <tablenames>  | Print details about <tablename>"
  putStrLn ":r               | Reload the schema"
  putStrLn ":q               | ToDo: quit"
  putStrLn "<querystring> | ToDo: run SELECT query"

runCommand :: Schema -> [String] -> IO ()
runCommand _ [] = return ()
runCommand schema (ident:as)
    | ident == ":h" = printHelp
    | ident == ":s" = prettyPrintSchema schema
    | ident == ":t" = prettyPrintTables.(map (\t -> M.lookup t schema))$as
    | ident == ":r" = setup
    | ident == ":q" = exitSuccess
    | otherwise     = runQuery schema (unwords (ident:as))

commandLoop :: Schema -> IO ()
commandLoop schema = do
  putStr "dbl# "
  command <- getLine
  runCommand schema (words command)
  putStrLn ""
  commandLoop schema

setup :: IO ()
setup = do
  putStrLn "\nEnter path to schema file"
  schemaPath <- getLine
  putStrLn ("\nTrying to load schema file \"" ++ schemaPath ++ "\"")
  schema <- readSchema schemaPath
  putStrLn "Loaded Schema"
  prettyPrintSchema schema
  putStrLn "Enter ':h' for help and a list of commands\n"
  commandLoop schema

sampleSetup :: IO ()
sampleSetup = do
  schema <- sampleSchema
  putStrLn "Loaded Schema"
  prettyPrintSchema schema
  putStrLn "Enter ':h' for help and a list of commands\n"
  commandLoop schema

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  setup