module Dodge.Creature.LtAutoCrit
    ( ltAutoCrit 
    ) where
import Dodge.Data
import Dodge.Default
import Dodge.Creature.Picture
import Dodge.Creature.Impulse
import Dodge.Creature.Action
import Dodge.Creature.Test
import Dodge.Creature.Volition
import Dodge.Creature.Strategy
--import Dodge.Creature.ChooseTarget
import Dodge.Creature.ReaderUpdate
import Dodge.Creature.Perception
import Dodge.Creature.State
--import Dodge.Creature.State.Data
import Dodge.Item.Weapon.BulletGuns
import Dodge.Item.Consumable
import Geometry
import Picture
--import Dodge.RandomHelp

--import Data.Maybe
import qualified Data.IntMap.Strict as IM
import Control.Lens
import Control.Monad.Reader
--import System.Random

ltAutoCrit :: Creature
ltAutoCrit = defaultCreature
    { _crPict = basicCrPict red
    , _crUpdate = stateUpdate $ impulsiveAIR $
        performActionsR
        >=> watchUpdateStratR
            [ (crHasTargetLOS, \_ _ -> StrategyActions (ShootAt 0) 
                [DoActionIf (not . crIsAiming) drawWeapon
                ,DoActionThen 
                    (DoActionWhile crHasTargetLOS $ ArbitraryAction chooseMovement)
                    (DoImpulses [ChangeStrategy WatchAndWait])
                ]
              )
            , (crAwayFromPost, goToPostStrat)
            ]
        >=> perceptionUpdate [0]
        >=> doStrategyActionsR
        >=> reloadOverrideR
        >=> targetYouWhenCognizantR
        >=> overrideInternalRRR
            (\cr -> (&&) <$> crHasTargetR cr <*> crStratConMatchesR (GetTo (V2 0 0)) cr)
            (pure . (crActionPlan . crStrategy .~ WatchAndWait))
    , _crActionPlan = ActionPlan
        { _crImpulse    = []
        , _crAction     = []
        , _crStrategy   = StrategyActions WatchAndWait [StartSentinelPost]
        , _crGoal       = []
        }
    , _crInv = IM.fromList [(0,ltAutoGun),(1,medkit 100)]
    , _crInvSel = 0
    , _crRad = 10
    , _crHP = 500
    }

chooseMovement :: Creature -> World -> Action
chooseMovement cr w 
    | dist cpos p > 200 = DoImpulses [UseItem,TurnToward p 0.05 , MoveForward 3]
    | dist cpos p < 80 = DoImpulses [UseItem,TurnToward p 0.05, MoveForward (-3) ]
    | errorAngleVV 22 (p' -.- cpos) (unitVectorAtAngle (_crDir cr)) < 0.4
          = DoImpulses [UseItem,TurnToward p' 0.01, Move (V2 0 3)]
    | otherwise
          = DoImpulses [UseItem,TurnToward p' 0.05, Move (V2 0 3)]
  where
    cpos = _crPos cr
    tcr = _creatures w IM.! 0
    p = _crPos tcr
    v = vNormal $ p -.- cpos
    p' = p +.+ 0.5 *.* (v -.- 20 *.* normalizeV v)
