module Dodge.Save
    ( saveWorldInEmptySlot
    , loadSaveSlot
    , doQuicksave
    )
  where
import Dodge.Data

import qualified Data.Map.Strict as M
import Data.Maybe
import Control.Lens
import qualified Data.Set as S

clearSaves :: World -> World
clearSaves = savedWorlds .~ M.empty

saveWorldInEmptySlot :: SaveSlot -> World -> World
saveWorldInEmptySlot slot w = case M.lookup slot $ _savedWorlds w of
    Nothing -> w & savedWorlds %~ M.insert slot (clearKeys w)
    _       -> w

saveWorldInSlot :: SaveSlot -> World -> World
saveWorldInSlot slot w = w & savedWorlds %~ M.insert slot (clearSaves $ clearKeys w)

loadSaveSlot :: SaveSlot -> World -> World
loadSaveSlot slot w = fromMaybe w 
    $ M.lookup slot (_savedWorlds w) 
        <&> savedWorlds .~ _savedWorlds w -- keep saves from current point, not from save point

doQuicksave :: World -> World
doQuicksave = saveWorldInSlot QuicksaveSlot

clearKeys :: World -> World
clearKeys = (keys .~ S.empty) . (mouseButtons .~ S.empty)
