module Dodge.Item.Weapon.AmmoParams
    ( useAmmoParams
    , ruseAmmoParamsRate
    , fractionLoadedAmmo
    , fractionLoadedAmmo2
    ) where
import Dodge.Data
import Dodge.Base
import Dodge.Particle.Bullet.Spawn
import Dodge.Creature.HandPos
import Dodge.Movement.Turn
import Geometry
import LensHelp

import Data.Maybe
--import Control.Lens

ruseAmmoParamsRate :: Int 
    -> HammerType
    -> [(Item -> Creature -> World -> World) -> Item -> Creature -> World -> World]
    -> ItemUse
ruseAmmoParamsRate rate ht usemods = RightUse
    { _rUse = useAmmoParams Nothing
    , _useDelay = FixedRate {_rateMax = rate,_rateTime = 0} 
    , _useMods = usemods
    , _useHammer = ht
    , _useAim = defaultAimParams
    , _heldScroll = \_ _ -> id
    }
defaultAimParams :: AimParams
defaultAimParams = AimParams
    { _aimWeight = 0
    , _aimRange = 0
    , _aimZoom = ItZoom 20 0.2 1
    , _aimStance = OneHand
    }
useAmmoParams :: Maybe Float -> Item -> Creature -> World -> World
useAmmoParams vfact it cr w = w & instantParticles .:~ aBulAt 
    vfact 
    thetraj                     -- extra update
    Nothing                     -- color (default)
    (Just cid)                  -- pass through creature
    sp
    (rotateV dir (muzvel *.* _amBulVel bultype))           -- vel
    (_rifling $ _itParams it)   -- drag
    (_amBulEff bultype) 
    (_amBulWth bultype) 
  where
    sp = _crPos cr +.+ muzlength *.* unitVectorAtAngle dir
    cid = _crID cr
    dir = _crDir cr
    bultype = _laAmmoType $ _itConsumption it
    muzvel = _muzVel $ _itParams it
    muzlength = aimingMuzzlePos cr it
    thetraj = case _amBulTraj bultype of
        BasicBulletTrajectory -> id
        MagnetTrajectory -> fromMaybe id $ do
            tpos <- it ^? itTargeting . tgPos . _Just
            return $ \pt -> pt & ptVel .+.+~ 5 *.* normalizeV (tpos -.- head (_ptTrail pt))
        FlechetteTrajectory -> fromMaybe id $ do
            tpos <- it ^? itTargeting . tgPos . _Just
            return $ \pt -> pt & ptVel %~ vecTurnTo 0.2 (head $ _ptTrail pt) tpos
        BezierTrajectory -> fromMaybe id $ do
            tpos <- it ^? itTargeting . tgPos . _Just
            let bf t = bQuadToF (sp,mouseWorldPos w,tpos) $ (100 - t) * 0.05
            return $ \pt -> pt 
                & ptVel .~ bf (fromIntegral $ _ptTimer pt - 1) -.- bf (fromIntegral $ _ptTimer pt)

---- this shouldn't really be used
loadedAmmo :: Item -> Int
loadedAmmo = _laLoaded . _itConsumption
--    | _laTransfer (_itConsumption it) == NoTransfer = _laLoaded (_itConsumption it)
--    | otherwise = 0

fractionLoadedAmmo :: Item -> Float
fractionLoadedAmmo it = fromIntegral (loadedAmmo it) / fromIntegral (itmaxammo it)
  where
    itmaxammo = _laMax . _itConsumption

fractionLoadedAmmo2 :: Item -> Float
fractionLoadedAmmo2 it = 1 - 
    (1 - fromIntegral (loadedAmmo it) / fromIntegral (itMaxAmmo it))**2
  where
    itMaxAmmo = _laMax . _itConsumption
