module Dodge.Item.Location where
import Dodge.Data
import qualified IntMapHelp as IM

import Control.Lens
import Data.Maybe

setHeldItemLoc :: Creature -> World -> World
setHeldItemLoc cr = fst . getHeldItemLoc cr

getHeldItemLoc :: Creature -> World -> (World,Int)
getHeldItemLoc cr w = case maybeitid of
    Nothing -> 
        ( w & creatures . ix cid . crInv . ix j . itID ?~ newitid
            & itemPositions %~ IM.insert newitid (InInv cid j)
        , itid)
    _ -> (w, itid)
  where
    cid = _crID cr
    j = crSel cr
    newitid = IM.newKey $ _itemPositions w
    maybeitid = cr ^? crInv . ix j . itID . _Just
    itid = fromMaybe newitid maybeitid

getItem :: Int -> World -> Maybe Item
getItem itid w = do
    itpos <- w ^? itemPositions . ix itid
    case itpos of
        OnFloor flitid -> w ^? floorItems . ix flitid . flIt
        InInv cid invid -> w ^? creatures . ix cid . crInv . ix invid

pointToItem :: Applicative f =>
                     ItemPos -> (Item -> f Item) -> World -> f World
pointToItem (InInv cid invid) = creatures . ix cid . crInv . ix invid
pointToItem (OnFloor flid) = floorItems . ix flid . flIt

