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

public class LimbBehaviour : MonoBehaviour {

    public KeyCode trigger;
    Animator m_Animator;

    public int currentHealth;
    public int MaxHealth;

    public string animationTrigger;
    public GameObject[] CatHooks;
    int damageCount = 0;

	public AudioSource Limb_Audio;
	public AudioClip[] Limb_AudioList;

    public GameObject[] physicalLimbs;

    public float hitwindow = 0.3f;
    public float activeHitWindow = 0.3f;


    // Use this for initialization
    void Start () {
        currentHealth = MaxHealth;
        GameObject player = GameObject.Find("Main");
        m_Animator = player.gameObject.GetComponent<Animator>();

        foreach (var go in CatHooks) {
            if (!go) Debug.LogWarning("CatHooks broken reference");
            if (go)
                go.SetActive(false) ;
        }

        foreach (var go in physicalLimbs) {
            

        }
        // run this when you get hit
        //m_Animator.speed -= 0.25;

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

        if (currentHealth < 0) { currentHealth = 0; }
        float checkVal = (((10.0f - (MaxHealth*2 - currentHealth*2)))/10.0f ) +0.0001f;

        
            if (Input.GetKeyDown(trigger) && Random.value < checkVal)
            {
                playAnimation();
                
                if ( Limb_AudioList != null  && Limb_AudioList.Length > 0) {
                    int CheckIndex = Random.Range(0, Limb_AudioList.Length);
                    //Debug.Log(CheckIndex);
                    Limb_Audio.PlayOneShot(Limb_AudioList[CheckIndex]);
                }

                activeHitWindow = hitwindow;
            }
        
        activeHitWindow -= Time.deltaTime;
    }

    public bool IsOnHitWindow() {
        return (activeHitWindow > 0);
    }

    public bool PhysicalBelongToLimb(GameObject phy) {
        foreach( var p in physicalLimbs) {
            if (p == phy) {
                return true;
            }
        }
        return false;
    }

    void playAnimation()
    {

        m_Animator.SetTrigger(animationTrigger);
    }

    public void OnAttacked() {
       //Debug.Log("OnAttacked"); 
        if (currentHealth == 0) return;
        --currentHealth;
        if (damageCount < CatHooks.Length) {
            if (CatHooks[damageCount]) {
                CatHooks[damageCount].SetActive(true);
            }
            ++damageCount;
            GlobalEvents.SendHPLossEvent();
        }
    }

}
