using UnityEngine;
using System.Collections;

public class SideBot2D : MonoBehaviour
{
    public float MaxSpeed = 10f;
    public LayerMask ObstacleLayerMask;
    public LayerMask HeroLayerMask;

    public bool IsGround;
    public bool IsFront;

    private bool _isFacingRight = true;

    private Transform _groundCheck;
    private Transform _frontCheck;
    const float CheckRadius = .3f; // Radius of the overlap circle to determine if grounded


    private Animator _anim;            // Reference to the player's animator component.
    private Rigidbody2D _rigidbody2D;

    private float _move;

    private void Awake()
    {
        _anim = GetComponent<Animator>();
        _rigidbody2D = GetComponent<Rigidbody2D>();

        _groundCheck = transform.Find("GroundCheck");
        _frontCheck = transform.Find("FrontCheck");
    }

    private void Update()
    {
    }

    private void FixedUpdate()
    {
        IsGround = false;
        Collider2D[] colliders = Physics2D.OverlapCircleAll(_groundCheck.position, CheckRadius, ObstacleLayerMask);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject != gameObject)
                IsGround = true;
        }

        IsFront = false;
        colliders = Physics2D.OverlapCircleAll(_frontCheck.position, CheckRadius, ObstacleLayerMask);
        for (int i = 0; i < colliders.Length; i++)
        {
            if (colliders[i].gameObject != gameObject)
                IsFront = true;
        }

        bool IsHero = false;

        if (IsGround == false || IsFront == true)
        {
            Flip();
        }
        else
        {
            colliders = Physics2D.OverlapCircleAll(_frontCheck.position, CheckRadius, HeroLayerMask);
            for (int i = 0; i < colliders.Length; i++)
            {
                if (colliders[i].gameObject != gameObject)
                    IsHero = true;
            }
        }

        _anim.SetBool("Attack_Tonfa", IsHero);
        if (IsHero == false)
        {
            _move = _isFacingRight ? 1 : -1;
            Move(_move);
        }
    }

    public void Move(float move)
    {
        // Move the character
        _rigidbody2D.velocity = new Vector2(move * MaxSpeed, _rigidbody2D.velocity.y);
    }

    private void Flip()
    {
        // Switch the way the player is labelled as facing.
        _isFacingRight = !_isFacingRight;

        // Multiply the player's x local scale by -1.
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
    }
}
