module Update.Update ( Action(..) , updates , update ) where import Signal import Dict import Dict (Dict) import Time (Time) import Maybe import Keyboard (KeyCode) import Char import Debug import List import Model.Model (..) import Model.Timer (..) import Model.TimerEdition (..) import Model.Id (..) import Model.IdGenerator (..) import Update.UpdateTimer (..) import Update.UpdateTimerEdition (..) import Utils.Maybe (..) type Action = NoOp | Initialize | AddNewTimer | DeltaTime Time | UpdateTimer Id TimerAction | RemoveTimer Id | EditTimer Id | ValidTimerEdition | ReadOnly | KeyPressed KeyCode updates : Signal.Channel Action updates = Signal.channel NoOp logUpdate : Action -> Model -> Model logUpdate action model = case action of DeltaTime _ -> update action model _ -> update (Debug.log "action" action) model update : Action -> Model -> Model update action model = case action of NoOp -> model Initialize -> initialModel model.currentTime AddNewTimer -> let (id, newTimerIdGenerator) = getId model.timerIdGenerator timerName = "Timer " ++ (toString id) in { model | timers <- Dict.insert id (initialTimer model.currentTime timerName) model.timers , timerIdGenerator <- newTimerIdGenerator } DeltaTime delta -> { model | currentTime <- model.currentTime + delta , timers <- Dict.map (\id timer -> updateTimer (SubstractTime delta) timer) model.timers } UpdateTimer id action -> let maybeTimerEdition = filterMaybe (\timerEdition -> timerEdition.id == id) model.timerEdition in case maybeTimerEdition of Just timerEdition -> { model | timers <- updateTimerTime timerEdition model.timers |> Dict.update id (Maybe.map (updateTimer action)) , timerEdition <- Nothing } Nothing -> { model | timers <- Dict.update id (Maybe.map (updateTimer action)) model.timers } RemoveTimer id -> if numberOfTimers model > 1 then { model | timers <- Dict.remove id model.timers } else model EditTimer id -> { model | timerEdition <- Just (newTimerEdition id) , timers <- Dict.update id (Maybe.map (updateTimer Pause)) model.timers } ValidTimerEdition -> case model.timerEdition of Just timerEdition -> { model | timers <- updateTimerTime timerEdition model.timers , timerEdition <- Nothing } Nothing -> { model | timerEdition <- Nothing } ReadOnly -> { model | timerEdition <- Nothing } KeyPressed keyCode -> if isRemoveKeyCode keyCode then { model | timerEdition <- Maybe.map (updateTimerEdition DeleteLast) model.timerEdition } else { model | timerEdition <- Maybe.map (updateTimerEdition (AddNumber keyCode)) model.timerEdition } updateTimerTime : TimerEdition -> Dict Id Timer -> Dict Id Timer updateTimerTime timerEdition = if List.isEmpty timerEdition.numbers then identity else Dict.update timerEdition.id (Maybe.map (updateTimer (SetTime (toTime timerEdition.numbers)))) isRemoveKeyCode : KeyCode -> Bool isRemoveKeyCode = (==) 8