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

public class LDAIMovement : TM_MovementComponent
{
    private GameManager theGame;
    private LDCameraManager mainCamera;

    public ETerrainType walkableTerrain;

    public LDGameActor myOwningActor;

    public float BaseMoveSpeedTilesPerSecond = 0.5f;


    public virtual void Awake()
    {
        theGame = GameManager.GetGame();
        mainCamera = Camera.main.GetComponent<LDCameraManager>();

    }

	// Use this for initialization
	void Start () 
    {
		
	}
	
	// Update is called once per frame
    public virtual void Update() 
    {
        CalculateMoveThisFrame();
	}

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

        if (_vGoalPosition == Vector2.zero)
        {
            return;
        }
        Vector2 vMyPos =  (Vector2)myOwningActor.vWorldPos;

        Vector2 vTowards = _vGoalPosition - vMyPos;

        vTowards.Normalize();

        Vector2 vDesiredPosition = vMyPos + vTowards * BaseMoveSpeedTilesPerSecond * Time.deltaTime;
        vDesiredPosition = CalculateWorldCollision(vMyPos, vDesiredPosition);

        _vDesiredMoveThisFrame += (Vector3)(vDesiredPosition - vMyPos);

        //draw debug line
        Vector3 vDrawPos =  mainCamera.transform.position;
        vDrawPos += (Vector3)_vGoalPosition - (Vector3)mainCamera.GetWorldPosition();
        vDrawPos.z = transform.position.z;

        Debug.DrawLine( transform.position, vDrawPos, Color.red, 0.2f, false);

    }


    public override Vector2 CalculateWorldCollision(Vector2 oldPosition, Vector2 desiredPosition)
    {
        //check to see if the desired position is in bounds
        ETerrainType terrain = theGame.theWorld.GetTerrainForTile(desiredPosition);
        if (terrain == walkableTerrain)
        {
            bWasStuck = false;
            return desiredPosition;
        }

        //otherwise, 
        bWasStuck = true;

        Vector2 vTryPos = new Vector2(oldPosition.x, desiredPosition.y);
        terrain = theGame.theWorld.GetTerrainForTile(vTryPos);
        if (terrain == walkableTerrain)
        {
            return vTryPos;
        }

        //one more time
        vTryPos = new Vector2(desiredPosition.x, oldPosition.y);
        terrain = theGame.theWorld.GetTerrainForTile(vTryPos);
        if (terrain == walkableTerrain)
        {
            return vTryPos;
        }

        return oldPosition;
    }

}
