module RogueLike.Update.Pickup where

import           RogueLike
import           RogueLike.Update

import           Data.Char             (digitToInt)
import           Data.List             ((!!))
import           Data.Map              (Map(..))
import qualified Data.Map as Map       (insert, lookup, delete)
import           Data.Maybe            (fromMaybe)
import           UI.NCurses            (Event(..))


updatePickup :: Event -> GameState -> GameState
updatePickup (EventCharacter eventChar) curGameState
    | eventChar == '\ESC'                  = curGameState{gameMode=GameMode}
    | eventChar >= '1' && eventChar <= '9' = pickupItem (digitToInt eventChar)
    | otherwise                            = curGameState
  where mapPos              = playerPos curGameState
        oldMapObjects       = gameObjects curGameState
        oldLocObjects       = fromMaybe  [] (Map.lookup mapPos oldMapObjects)
        oldInventory        = inventory curGameState
        newInventory index  = oldLocObjects !! (index - 1)
        newLocObjects index = oldLocObjects `withOut` index
        newMapObjects index =
            if length oldLocObjects == 1
                then Map.delete mapPos oldMapObjects
                else Map.insert mapPos (newLocObjects index) oldMapObjects
        pickupItem index    =
            if index > length oldLocObjects
                then curGameState
                else curGameState{gameObjects=newMapObjects index,inventory=newInventory index : oldInventory, gameMode=GameMode}
updatePickup _ curGameState = curGameState
