{-# LANGUAGE ForeignFunctionInterface #-}

module Main where

import TypesAndConstants
import qualified ProgramLogic as PL

import System.IO
import Graphics.UI.Gtk hiding (Settings)
import Control.Concurrent (forkIO)
import Control.Monad.State (evalStateT)
import System.Console.Haskeline
import Graphics.X11.Xlib (initThreads)
import Data.List


completionList = [ ":save", ":load", ":help", ":exit", "fw", "rot", "chg", "rep", "clear", "reset"]

searchFunc :: String -> [Completion]
searchFunc str = map simpleCompletion $ filter (str `isPrefixOf`) completionList

mySettings :: Settings IO
mySettings = Settings { complete = completeWord Nothing " \t" $ return . searchFunc
                      , historyFile = Nothing
                      , autoAddHistory = True
                      }


main :: IO ()
main = do
  initThreads
  initGUI
  window <- windowNew
  set window [windowTitle := "No Turtle"
             , windowAllowGrow := False
             , windowDefaultWidth := windowWidth
             , windowDefaultHeight := windowHeight ]
  widgetSetSizeRequest window windowWidth windowHeight

  frame <- frameNew
  containerAdd window frame
  
  canvas <- drawingAreaNew
  containerAdd frame canvas
  
  widgetModifyBg canvas StateNormal (Color 65535 65535 65535)
  

  widgetShowAll window
  onDestroy window mainQuit

  dw <- widgetGetDrawWindow canvas
  let initPoint = (fromIntegral(div windowHeight 2) :: Double, fromIntegral(div windowWidth 2) :: Double)

  threadId <- forkIO $ runInputT mySettings $
                         evalStateT PL.programLoop (ProgramState { lastPoint = initPoint
                                                                 , color = (0,0,0)
                                                                 , angle = 0 
                                                                 , incCommStack = []
                                                                 , drawWindow = dw
                                                                 , drawing = return ()})
  mainGUI