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

import Control.Monad
import Control.Lens
import SDL

handlePressedKeyInMenu :: ScreenLayer -> Scancode -> World -> Maybe World
handlePressedKeyInMenu mState scode = case mState of
    OptionScreen { _scOptions = mos, _scDefaultEff = defeff} 
                        -> optionListToEffects mos defeff scode
    DisplayScreen {}    -> popScreen
    ColumnsScreen {}    -> popScreen
    WaitScreen {}       -> Just
    TerminalScreen 0 _  -> popScreen
    TerminalScreen _ m  -> Just . ( menuLayers %~ ( (TerminalScreen 0 m : ) . tail) )
    InputScreen s       -> case scode of
        ScancodeEscape  -> popScreen
        ScancodeReturn  -> popScreen . applyTerminalString s
        ScancodeBackspace 
            -> popScreen >=> pushScreen (InputScreen $ dropLast s)
        _   -> popScreen >=> pushScreen (InputScreen $ s ++ [scodeToChar scode])
  where 
    dropLast (x:xs) = init (x:xs)
    dropLast _      = []
optionListToEffects :: [MenuOption] -> (World -> Maybe World) -> Scancode -> World -> Maybe World
optionListToEffects mos defaulteff sc w = case lookup sc listEffects of
    Nothing -> defaulteff w
    Just eff -> eff w
  where
    listEffects = concatMap menuOptionToEffects mos

menuOptionToEffects :: MenuOption -> [(Scancode,World -> Maybe World)]
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)]
