module Dodge.Item.Draw 
    ( pictureWeaponOnAim
    , pictureWeaponAim
    , twoFlatHRot
    , itSPic
    ) where
import Dodge.Data
--import Dodge.Picture.Layer
--import Picture
--import Shape
import ShapePicture
import Dodge.Creature.HandPos

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

pictureWeaponOnAim
    :: Creature 
    -> Item
    -> SPic
pictureWeaponOnAim = pictureWeaponAim itSPic

itSPic :: Item -> SPic
itSPic it = _dimSPic (_itDimension it) it

pictureWeaponAim
    :: (Item -> SPic)
    -> Creature 
    -> Item
    -> SPic
pictureWeaponAim f cr itm = case _itInvPos itm of
    Just i -> pictureWeaponOnAimItem (f itm) cr i
    Nothing -> mempty

{- | Places an item picture onto a creature when the item is selected. -}
pictureWeaponOnAimItem
    :: SPic 
    -> Creature 
    -> Int  -- ^ Position of item in inventory
    -> SPic
pictureWeaponOnAimItem p' cr posInInv 
    | isSelected && _posture (_crStance cr) == Aiming =
        shoulderD $ translateSPf (aimingWeaponZeroPos cr theIt) 0 p'
    | isSelected && isTwoHandFlat
                = handD holsteredTwoFlat
    | isSelected && isOneHand
                = handD holsteredOneHandWep
    | isSelected 
                = handD holsteredWep
    | otherwise = emptyBlank
  where 
    shoulderD = translateSPz 18
    handD = translateSPz 15
    isSelected = crSel cr == posInInv 
    twistWep        = translateSPf (-5) 0 p
    holsteredWep    = translateSPf (_crRad cr) 0 
        (rotateSP (strideRot cr + 1.2) (translateSPf (-5) 0 twistWep))
    holsteredTwoFlat    = translateSPf (_crRad cr) 0 (rotateSP (twoFlatHRot cr) p)
    holsteredOneHandWep = translateSPf (_crRad cr * 0.7 + handPos) (_crRad cr * negate 0.7) 
        (translateSPf (-2) 0 p)
    handPos = case cr^? crStance . carriage of
        Just (Walking x LeftForward) -> f x * 50
        _ -> 0
    theIt = _crInv cr IM.! posInInv
    p = fromMaybe p' $ do
        x <- theIt ^? itDimension . dimPortage . handlePos
        return $translateSPf (-x) 0 p'
    isOneHand       = theIt ^? itUseAimStance == Just OneHand
                        || isNothing (theIt ^? itUseAimStance)
    isTwoHandFlat   = theIt ^? itUseAimStance == Just TwoHandFlat
    itUseAimStance = itUse . useAim . aimStance   
    f i = 0.1 * fromIntegral (sLen - i) / fromIntegral sLen
    sLen = _strideLength $ _crStance cr


strideRot :: Creature -> Float
strideRot cr = case cr ^? crStance . carriage of
    Just (Walking x LeftForward)  -> f x
    Just (Walking x RightForward) -> - f x
    _ -> 0
  where
    f i = 0.1 * fromIntegral (sLen - i) / fromIntegral sLen
    sLen = _strideLength $ _crStance cr

twoFlatHRot :: Creature -> Float
twoFlatHRot cr = 2*strideRot cr
