using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Debugging;
using Framework.Extensions;

public class WanderingBehaviour : CoreBehaviour
{
    public class StartAutoMoveAction : CoreAction { }
    public class StopAutoMoveAction : CoreAction { }

    private Vector3 startPosition;

    public bool moving = true;
    public Vector3 targetPosition;
    public Vector3 targetMask = new Vector3(1,0,1);

    protected override void InnerAwake()
    {
        AddActionHandler<StartAutoMoveAction>((StartAutoMoveAction action) => { moving = true; });
        AddActionHandler<StopAutoMoveAction>((StopAutoMoveAction action) => { moving = false; });
        this.startPosition = this.transform.position;
        SetRandomTargetPosition();
    }

    protected override void InnerUpdate()
    {
        if (moving)
        {
            if (Vector3.Distance(this.transform.position.ProjectRelative(this.transform, targetMask), this.targetPosition.ProjectRelative(this.transform, targetMask)) < 0.5f)
            {
                SetRandomTargetPosition();
            }
            Draw.Axis(this.targetPosition, Color.blue);
            Interact(new MoveAction(this.targetPosition));
            Interact(new TurnAction(this.targetPosition));
        }
    }

    private void SetRandomTargetPosition()
    {
        RaycastHit hit;
        Vector3 randomPosition = this.startPosition + new Vector3(Random.Range(-5, 5), 50, Random.Range(-5, 5));
        if (Physics.Raycast(randomPosition, Vector3.down, out hit, 100)) // , 1 << LayerMask.NameToLayer("Ground")
        {
            this.targetPosition = hit.point;
        }
    }
}
