using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Monster : MonoBehaviour {

    public float health;

    protected CharacterController character;

    protected GameObject playerReference;

    public float value;

    Vector3 knockbackForce;

    float knockbackTime;

    GlobalManager manager;

    public bool alive { get { return health > 0; } }

    public GameObject deathEffect;

    void Start()
    {
        character = GetComponent<CharacterController>();
        playerReference = GameObject.FindGameObjectWithTag("Player");
        manager = GameObject.FindGameObjectWithTag("GameController").GetComponent<GlobalManager>();
    }

    protected bool GlobalUpdate()
    {
        if (playerReference == null)
            return false;

        if (manager.frozen)
            return false;

        return true;
    }

    protected bool GlobalFixedUpdate()
    {
        if (playerReference == null)
            return false;

        if (IsStunned())
        {
            ManageKnockback();
            return false;
        }

        if (manager.frozen)
            return false;

        return true;
    }

    public void TakeDamage(float damage)
    {
        health -= damage;
        if (health <= 0)
            Kill();
    }

    public void Kill()
    {
        if (deathEffect != null)
        {
            GameObject effect = GameObject.Instantiate(deathEffect, transform.position, Quaternion.identity);
            GameObject.Destroy(effect, 1);
        }
        GameObject.Destroy(gameObject);
    }

    public void Knockback(Vector3 force)
    {
        knockbackForce = force;
        knockbackTime = 0.2f;
    }

    public bool IsStunned()
    {
        return knockbackTime > 0;
    }

    protected void ManageKnockback()
    {
        knockbackTime -= Time.deltaTime;
        if (knockbackTime > 0)
        {
            character.Move(knockbackForce * Time.deltaTime);
        }
    }
}
