using UnityEngine;
using System.Collections;

public class OozeBall : MonoBehaviour
{
    private Animator animator;

    public AudioClip spawnSound;

    public AudioClip bounceSound;

    public AudioClip hitSound;

    public AudioClip timerSound;

    public AudioClip splitSound;

    public AudioClip stoppedSound;

    public BallSpawner spawner;

    private AudioSource audioSource;

    private SpriteRenderer spriteRenderer;

    private Vector2 speed;

    private float splitTimer = 10.0f;

    private float tickTimer = 0.5f;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        animator = GetComponent<Animator>();
        spriteRenderer = GetComponent<SpriteRenderer>();
        speed = new Vector2(Random.Range(-0.002f, 0.002f), Random.Range(-0.002f, 0.002f));

        audioSource.PlayOneShot(spawnSound);
    }

    // Update is called once per frame
    void Update()
    {
        AnimatorStateInfo stateInfo = animator.GetCurrentAnimatorStateInfo(0);

        if (stateInfo.IsName("OozeBallMove") || stateInfo.IsName("OozeBallSplit")) {
            transform.Translate(speed);
        }

        splitTimer -= Time.deltaTime;
        tickTimer -= Time.deltaTime;

        if (splitTimer <= 0.0f)
        {
            animator.SetTrigger("split");
        }

        if (tickTimer <= 0.0f)
        {
            tickTimer = 0.5f;
            audioSource.PlayOneShot(timerSound);
        }

        // TODO: Implement logic to halt the OozeBall's splitting behavior.
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Wall"))
        {
            ContactPoint2D contact = collision.GetContact(0);
            speed = Vector2.Reflect(speed, contact.normal);
        }
    }

    void Split()
    {
        StartCoroutine(SplitCoroutine());
    }

    private IEnumerator SplitCoroutine()
    {
        spriteRenderer.enabled = false;
        audioSource.PlayOneShot(splitSound);

        for (int i = 0; i < Random.Range(5, 8); i++)
        {
            Vector3 spawnPosition = transform.position +
                                    new Vector3(Random.Range(-0.12f, 0.12f), Random.Range(-0.12f, 0.12f), 0);
            spawner.SpawnBallOfType("BasicBall", spawnPosition);
        }

        spawner.FixCollisions();

        yield return new WaitForSeconds(1.0f);

        Destroy(gameObject);
    }

    void Halt()
    {
        audioSource.PlayOneShot(stoppedSound);
        // TODO: Implement the logic for transforming the OozeBall into a basic ball.
    }
}
