module Update.Update ( Action(..) , updates , logUpdate , update ) where import Signal import Dict import Dict (Dict) import Time (Time) import Maybe import Keyboard (KeyCode) import Char import List import Debug import Model.Model (..) import Model.Timer (..) import Model.Edition.Edition (..) import Model.Edition.NameEdition (..) import Model.Edition.TimeEdition (..) import Model.Id (..) import Model.IdGenerator (..) import Update.UpdateTimer (..) import Update.UpdateEdition (..) import Utils.Maybe (..) type Action = NoOp | Initialize | AddNewTimer | DeltaTime Time | UpdateTimer Id TimerAction | RemoveTimer Id | Edit Id Kind | ClickAway | 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 in { model | timers <- Dict.insert id (initialTimer model.currentTime) model.timers , timerIdGenerator <- newTimerIdGenerator } DeltaTime delta -> { model | currentTime <- model.currentTime + delta , timers <- Dict.map (\id timer -> updateTimer (SubstractTime delta) timer) model.timers } UpdateTimer id timerAction -> let maybeEdition = filterMaybe (\edition -> edition.id == id) model.edition newModel = case maybeEdition of Just edition -> if edition.kind == Time then validEdition model else model Nothing -> model in { newModel | timers <- Dict.update id (Maybe.map (updateTimer timerAction)) newModel.timers } RemoveTimer id -> if numberOfTimers model > 1 then { model | timers <- Dict.remove id model.timers } else model Edit id kind -> { model | edition <- Just (newEdition id kind) , timers <- if kind == Time then Dict.update id (Maybe.map (updateTimer Pause)) model.timers else model.timers } ClickAway -> { model | edition <- Nothing } KeyPressed keyCode -> if isEnterKeyCode keyCode then validEdition model else let editionAction = if isRemoveKeyCode keyCode then DeleteLast else AddChar keyCode in { model | edition <- Maybe.map (updateEdition editionAction) model.edition } validEdition : Model -> Model validEdition model = case model.edition of Just edition -> if List.isEmpty edition.chars then model else let timerAction = case edition.kind of Name -> Rename (renderNameEdition edition.chars) Time -> SetTime (toTime edition.chars) in { model | timers <- Dict.update edition.id (Maybe.map (updateTimer timerAction)) model.timers , edition <- Nothing } Nothing -> model isEnterKeyCode : KeyCode -> Bool isEnterKeyCode = (==) 13 isRemoveKeyCode : KeyCode -> Bool isRemoveKeyCode = (==) 8