using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LDProjectileMovementComponent : TM_MovementComponent
{
    public TM_Projectile myProjectile;
    public bool MustConvertTransformToGamePos;
    private bool bMovementWasForcedThisTick;
    private Vector3 vForcedMove;
    private GameManager theGame;
    private LDGameActor myActor;
    private LDGameActor theActorWhoFiredTheWeaponThatFiredMe;

    [Header("Heat Seeking!")]
    public bool ShouldSeekTarget;
    private LDGameActor LockOnTarget;
    public float LockOnSpeed;



    public virtual void Start()
    {
        theGame = GameManager.GetGame();

        myActor = GetComponent<LDGameActor>();
        if (myActor != null )
        {
            if( MustConvertTransformToGamePos )
            {
                myActor.vWorldPos = theGame.GetGameWorldPositionFromTransformPosition(transform.position);
            }

            if (myProjectile != null && myProjectile.owningCombatComponent != null)
            {
                theActorWhoFiredTheWeaponThatFiredMe = myProjectile.owningCombatComponent.GetComponent<LDGameActor>();
            }

            if (theActorWhoFiredTheWeaponThatFiredMe != null && ShouldSeekTarget)
            {
                LockOnTarget = theActorWhoFiredTheWeaponThatFiredMe.GetLastTarget();
                
            }
        }

    }

    public void SetForcedMovement(Vector2 vFrom, Vector2 vTo)
    {
        vForcedMove = vTo - vFrom;
        vForcedMove.z = 0f;

        bMovementWasForcedThisTick = true;
    }

    public override void CalculateMoveThisFrame()
    {
        base.CalculateMoveThisFrame();

        if (LockOnTarget == null || LockOnTarget.IsDead())
        {
            ShouldSeekTarget = false;
        }

        //add an impulse pushing us toward our target
        if (ShouldSeekTarget && LockOnTarget != null)
        {
            Vector2 vToTarget = LockOnTarget.vWorldPos - myActor.vWorldPos;
            vToTarget.Normalize();
            AddImpulse(vToTarget * LockOnSpeed, 0f);
        }
    }

    public void Update()
    {
        CalculateMoveThisFrame();
    }

    public override Vector3 GetDesiredMove()
    {
        if (bMovementWasForcedThisTick)
        {
            bMovementWasForcedThisTick = false;
            return vForcedMove;
        }

        return (myProjectile.fSpeed * myProjectile.vDirection * Time.deltaTime) + _vDesiredMoveThisFrame;
    }
}
