using UnityEngine;
using System.Collections;

public abstract class YummyBase : NotifierBase
{
    public AudioClip bounceSound;

    public AudioClip obtainedSound;

    public AudioClip missedSound;

    private AudioSource audioSource;

    private Animator animator;

    private SpriteRenderer spriteRenderer;

    private Vector2 speed;

    private bool isObtained = false;

    private float missedTimer = 0f;

    private bool isMissed = false;

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

    // Update is called once per frame
    void FixedUpdate()
    {
        if (isObtained || isMissed)
        {
            return;
        }
        
        // Force reset the rotation.
        transform.rotation = Quaternion.identity;
        transform.Translate(speed);

        missedTimer += Time.fixedDeltaTime;

        if (missedTimer >= 5f && !isMissed)
        {
            isMissed = true;
            audioSource.PlayOneShot(missedSound);
            animator.SetTrigger("missed");
            StartCoroutine(DestroyYummy());
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (isObtained)
        {
            return;
        }

        if(other.gameObject.CompareTag("Bar"))
        {
            var player = GameObject.FindGameObjectWithTag("Player");
            Obtain(player.GetComponent<Player>());
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Wall"))
        {
            ContactPoint2D contact = collision.GetContact(0);
            speed = Vector2.Reflect(speed, contact.normal);
            audioSource.PlayOneShot(bounceSound);
        }
        else
        {
            Physics2D.IgnoreCollision(collision.collider, GetComponent<Collider2D>(), true);
        }
    }

    public IEnumerator DestroyYummy()
    {
        yield return new WaitForSeconds(1.5f);
        Destroy(gameObject);
    }

    public void AwardToPlayer(Player player)
    {
        Obtain(player);
    }

    private void Obtain(Player player)
    {
        if (isObtained || isMissed)
        {
            return;
        }

        audioSource.PlayOneShot(obtainedSound);

        if (player != null)
        {
            ObtainedCallback(player);
        }

        isObtained = true;
        spriteRenderer.enabled = false;
    }

    protected abstract void ObtainedCallback(Player player);
}
