module GTKInitialization
  ( initUI
  , buildUI
  , setupUI
  , startUI
  ) where


import BattleContext
import GTKContext
import GTKMainWindow
import GTKButtonPanel
import GTKOverlay
import GTKUnit

import qualified Data.Text as DT
import Data.IORef
import Control.Monad.Trans
import Control.Monad.Trans.Reader


import qualified GI.Gtk as Gtk

-- import System.IO.Unsafe
-- import Data.IORef
-- import qualified Data.Text as DT
-- import System.FilePath
-- import Data.Maybe
-- import Control.Monad

-- import Data.GI.Base
-- import qualified GI.Gtk as Gtk
-- import qualified GI.GdkPixbuf as GP

-- -- cairo/gi-cairo stuff
-- import qualified GI.Cairo as GI.Cairo
-- import Graphics.Rendering.Cairo
-- import Graphics.Rendering.Cairo.Internal (Render(runRender))
-- import Graphics.Rendering.Cairo.Types (Cairo(Cairo))
-- import Foreign.Ptr (castPtr)
-- import Control.Monad.Trans.Reader


-- | Early initialization of GTK
initUI ::  IO ()
initUI = Gtk.init Nothing



-- | Build GTK ui (both builder and manual widgets) and return its program context
buildUI :: BattleContext -> FilePath -> IO GTKContext
buildUI bctx datadir = do
  let f = (uctxDataDir uctx) ++ "/ui-main.glade"
  builder <- Gtk.builderNewFromFile (DT.pack f)

  -- fetch and construct gtk units
  let blueforce = bctxBlueForce bctx
  let redforce = bctxRedForce bctx
  let iconsdir = datadir ++ "/Icons"

  bluegus <- liftIO $ constructForceUnitWidgets iconsdir blueforce
  redgus <- liftIO $ constructForceUnitWidgets iconsdir redforce

  -- mutable battle context
  bctxref <- newIORef bctx

  -- gtk units are stored in a mutable list to modify them on the fly
  gunitsref <- newIORef $ bluegus ++ redgus

  -- attach click events in the gtk context to all units' event boxes
--  _ <- liftIO $ Gtk.onWidgetButtonPressEvent evbox (runReaderT btnOrbatClicked gtkctx)


  return $ GTKContext
    { gctxBattleContext = bctxref
    , gctxDataDir = datadir
    , gctxBuilder = builder
    , gctxUnitWidgets = gunitsref
    }


-- | Set up signal handlers, widgets, etc in GTK program context
setupUI :: ReaderT GTKContext IO ()
setupUI = do
  setupMainWindow
  setupButtons
  setupOverlay

  return ()

-- | Run the GTK program
startUI :: ReaderT GTKContext IO ()
startUI = do
  liftIO $ Gtk.main


