using System;
using UnityEngine;
using System.Collections;
using Random = UnityEngine.Random;

public class GoombaScript : MonoBehaviour
{
    public float speed;
    public float deathSpeed;
    public int health;
    public int direction = 1;
    public AudioClip deathClip;
	// Use this for initialization
	void Start ()
	{
	    GameObject.FindGameObjectWithTag("Level").GetComponent<LevelScript>().remainingEnemies += 1;
	}

    private void Destroy()
    {
        Destroy(gameObject);
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (!collision.gameObject.tag.Equals("Ground"))
        {
            var hit = collision.contacts[0].normal;
            if (Mathf.RoundToInt(hit.x) == 1 || Mathf.RoundToInt(hit.x) == -1)
            {
                direction = -direction;
            }
        }
        if (collision.gameObject.tag.Equals("Bullet"))
        {
            AudioSource.PlayClipAtPoint(deathClip, transform.position);
            health = 0;
            var script = GameObject.FindGameObjectWithTag("Level").GetComponent<LevelScript>();
            script.remainingEnemies -= 1;
            script.state = LevelScript.GameState.Hit;
            
        }
    }

    // Update is called once per frame
	void FixedUpdate () {

	    if (health <= 0)
	    {
           
            GetComponent<Animator>().SetBool("isAlive", false);
	        GetComponent<BoxCollider2D>().enabled = false;
            Invoke("Destroy",1);
            GetComponent<Rigidbody2D>().AddForce(new Vector2(0,0.1f));
            transform.Rotate(new Vector3(0,0,1),deathSpeed);
	    }
	    else
	    {
            GetComponent<Rigidbody2D>().velocity = new Vector2(direction * speed, GetComponent<Rigidbody2D>().velocity.y);
            transform.eulerAngles = new Vector3(0,0,0);
	    }
	}
}
