using UnityEngine;

public class ControlIndicator : MonoBehaviour 
{
    public float SwitchTime = 0.4f;
    public float ShowTime = 0.4f;
    public Vector2 Offset = Vector2.up;

    private Transform target;
    private Vector2 startPos;
    private float lastSwitch;
    private Vector2 origScale;

    public void SetTarget(Transform t)
    {
        if (t == null || t == target)
            return;

        if (target == null)
        {
            startPos = t.position;
            lastSwitch = Time.time - SwitchTime;
        }
        else
        {
            startPos = (Vector2)target.position + Offset;
            lastSwitch = Time.time;
        }
           
        target = t;
    }

	void Start () 
	{
        origScale = transform.localScale;
    }
	
	void Update () 
	{
        if (target == null || Time.time > lastSwitch + SwitchTime + ShowTime)
            Clear();

        else if (Time.time > lastSwitch + SwitchTime)
            Show();

        else if (Time.time > lastSwitch)
            Switch();
    }

    private void Clear()
    {
        transform.localScale = Vector3.zero;
    }

    private void Show()
    {
        float portion = (Time.time - (lastSwitch + SwitchTime)) / ShowTime;  // moves from 0 to 1
        float size = (portion < 0.5f) ? (1 + 2 * portion) : 4 - (4 * portion);
        transform.localScale = origScale * size;
        transform.position = (Vector2)target.position + Offset;
    }

    private void Switch()
    {        
        float portion = (Time.time - lastSwitch) / SwitchTime;  // moves from 0 to 1
        transform.localScale = (0.4f + 0.4f*portion) * origScale;
        transform.position = (1 - portion) * startPos + portion * ((Vector2)target.position + Offset);
    }
}
