module Dodge.Creature.Impulse.UseItem
    ( useItem
    , tryUseItem
    , useLeftItem
    )
    where
import Dodge.Data
import Dodge.Inventory

import qualified Data.IntMap.Strict as IM
import Control.Lens
import Data.Maybe

useItem :: Int -> World -> World
useItem n w = itemEffect c it w
  where 
    c = _creatures w IM.! n
    it = _crInv c IM.! _crInvSel c

tryUseItem 
    :: Creature      
    -> World 
    -> World
tryUseItem cr' w = case w ^? creatures . ix (_crID cr') of
    Just cr -> itemEffect cr (_crInv cr IM.! _crInvSel cr) w
    Nothing -> w

itemEffect 
    :: Creature    
    -> Item 
    -> World 
    -> World
itemEffect cr Consumable{_cnEffect=eff } w = maybe w (rmSelectedInvItem (_crID cr)) (eff (_crID cr) w)
itemEffect cr it@Weapon{_itUse=eff} w = foldr ($) eff (_itUseModifiers it) it cr w
itemEffect cr it@Throwable{_itUse = eff} w = foldr ($) eff (_itUseModifiers it) it cr w
itemEffect _ _ w = w

useLeftItem
    :: Int
    -> World
    -> World
useLeftItem cid w = case luse of
    Nothing -> w
    Just (invid, f) -> f cr invid w
  where
    cr = _creatures w IM.! cid
    luses = IM.mapMaybe (^? itLeftClickUse . _Just) (_crInv cr)
    luse = listToMaybe $ IM.toList luses
