﻿using UnityEngine;
using System.Collections;
using Arbor;

/// <summary>
/// Turn to the direction of the object specified by Tag.
/// </summary>
public class LookAt2DObjectWithTag : StateBehaviour
{
	/// <summary>
	/// Transform to turn.
	/// </summary>
	[SerializeField] private Transform _Transform = null;

	/// <summary>
	/// Target tag
	/// </summary>
	[SerializeField] private string _Tag = "";

	/// <summary>
	/// Flag to apply with LateUpdate.
	/// </summary>
	[SerializeField] private bool _ApplyLateUpdate = false;

	void Awake()
	{
		// If _Transform is null, do GetComponent.
		if (_Transform == null)
		{
			_Transform = GetComponent<Transform>();
		}
	}

	void LookAt()
	{
		// Find the GameObject by Tag.
		GameObject target = GameObject.FindWithTag(_Tag);
		if (_Transform != null && target != null)
		{
			// Turn to the target.
			_Transform.LookAt2D(target.transform, Vector2.up);
		}
	}

	// Use this for enter state
	public override void OnStateBegin()
	{
		// Turn around at the beginning of the state.
		LookAt();
	}

	void LateUpdate()
	{
		if (_ApplyLateUpdate)
		{
			// If _ApplyLateUpdate is true, turn around with LateUpdate().
			LookAt();
		}
	}
}
