using UnityEngine;
using System.Collections;

public class OozeBall : BallBase
{
    public AudioClip timerSound;

    public AudioClip splitSound;

    public AudioClip stoppedSound;

    public BallSpawner spawner;

    private SpriteRenderer spriteRenderer;

    private Bounds boardBounds;

    private Collider2D selfCollider;

    private bool hasBoardBounds = false;

    private float magnetBounceDuration = 0.35f;

    private float magnetCenterLeeway = 0.12f;

    private MagnetBounceAxisState xMagnetBounceState;

    private MagnetBounceAxisState yMagnetBounceState;

    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>();
        selfCollider = GetComponent<Collider2D>();
        speed = new Vector2(Random.Range(-0.05f, 0.05f), Random.Range(-0.05f, 0.05f));

        hasBoardBounds = TryCacheGameBoardBounds(out boardBounds);

        audioSource.PlayOneShot(spawnSound);
    }

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

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

            if (affectedByMagnet && hasBoardBounds)
            {
                Vector3 currentPosition = transform.position;

                currentPosition.x = ApplyMagnetBounceAxis(
                    currentPosition.x,
                    boardBounds.min.x,
                    boardBounds.max.x,
                    magnetActiveLeftRight,
                    ref xMagnetBounceState,
                    selfCollider != null ? selfCollider.bounds.extents.x : 0.0f,
                    magnetBounceDuration,
                    magnetCenterLeeway
                );

                currentPosition.y = ApplyMagnetBounceAxis(
                    currentPosition.y,
                    boardBounds.min.y,
                    boardBounds.max.y,
                    magnetActiveTopBottom,
                    ref yMagnetBounceState,
                    selfCollider != null ? selfCollider.bounds.extents.y : 0.0f,
                    magnetBounceDuration,
                    magnetCenterLeeway
                );

                transform.position = currentPosition;
            }
        }

        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);
        }
        else
        {
            Physics2D.IgnoreCollision(collision.collider, GetComponent<Collider2D>(), true);
        }
    }

    public 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);
    }

    public void Halt()
    {
        StartCoroutine(HaltCoroutine());
    }

    private IEnumerator HaltCoroutine()
    {
        spriteRenderer.enabled = false;
        audioSource.PlayOneShot(stoppedSound);
        spawner.SpawnBallOfType("BasicBall", transform.position);

        yield return new WaitForSeconds(0.53f);

        Destroy(gameObject);
    }
}
