module Dodge.Event.Menu
    ( handlePressedKeyInMenu
    ) where
import Dodge.Data
import Dodge.Debug.Terminal
--import Dodge.Menu
import Dodge.Menu.PushPop
import Dodge.WindowLayout

import Data.Maybe
--import Control.Monad
import Control.Lens
import SDL
--import qualified Debug.Trace
import qualified Data.Text as T

handlePressedKeyInMenu :: ScreenLayer -> Scancode -> Universe -> IO (Maybe Universe)
handlePressedKeyInMenu mState scode = case mState of
    OptionScreen { _scOptions = mos, _scDefaultEff = defeff}
                        -> optionListToEffects defeff scode mos
    DisplayScreen {}    -> popScreen
    ColumnsScreen {}    -> popScreen
    WaitScreen {}       -> return . Just
    InputScreen s help  -> case scode of
        ScancodeEscape      -> popScreen
        ScancodeReturn      -> popScreen . applyTerminalString (words $ T.unpack s)
        ScancodeTab         -> autoCompleteTerminal (T.unpack s) help
        ScancodeBackspace   -> return . Just . (menuLayers . ix 0 . scInput %~ doBackspace)
        -- text input handled by handleTextInput
        _                   -> return . Just
  where
    doBackspace t = case T.unsnoc t of
        Nothing -> t
        Just (t',_) -> t'

optionListToEffects 
    :: (Universe -> IO (Maybe Universe)) 
    -> Scancode
    -> [MenuOption]
    -> Universe -> IO (Maybe Universe)
optionListToEffects defaulteff sc mops u = case sc of
    ScancodeSpace -> return . Just 
        . (menuLayers . ix 0 . scOptionsOffset %~ (f . (+ mlines)))
        $ u
    _ -> (fromMaybe defaulteff
        . lookup sc 
        . concatMap menuOptionToEffects $ mops) u
  where
    f x | x > length mops = 0
        | otherwise = x
    mlines = availableMenuLines $ _config u

menuOptionToEffects :: MenuOption -> [(Scancode,Universe -> IO (Maybe Universe))]
menuOptionToEffects Toggle          {_moKey = k, _moEff = eff} = [(k,eff)]
menuOptionToEffects InvisibleToggle {_moKey = k, _moEff = eff} = [(k,eff)]
menuOptionToEffects Toggle2
    { _moKey1 = k1
    , _moEff1 = eff1
    , _moKey2 = k2
    , _moEff2 = eff2
    } = [(k1,eff1) , (k2,eff2)]
