﻿using UnityEngine;
using System.Collections;

public class KoopaScript : MonoBehaviour {

    public float speed;
    public float deathSpeed;
    public int health;
    public int direction = 1;
    public float jumpForce;
    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;
                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y,
                    transform.localScale.z);
            }
        }
        else
        {
            Jump();
        }
        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;
        }
        
    }

    private void Jump()
    {
        rigidbody2D.AddForce(new Vector2(0,jumpForce));
    }
	
	// Update is called once per frame
	void FixedUpdate () {

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