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

public class catBody : MonoBehaviour {

    bool attacked = false;
    bool OnTopBed ;

    // Use this for initialization
    void Start () {
        OnTopBed = false;
    }
    
    // Update is called once per frame
    void Update () {
        
    }

    void OnTriggerEnter(Collider other) {
        Debug.Log("catBody trigger");
        Debug.Log(other.tag);
        //Debug.Log(other.name);
        if (other.CompareTag("bedTop"))
        {
            if (attacked) {
                Debug.LogWarning("Already triggered");
            }
            var c = transform.parent.GetComponent<CatBasicAIBehaviour>();
            if (!c) Debug.LogWarning("catbody: ontriggerenter: no ai");
            c.OnTriggered(other);
            attacked = true;
        }

        if (other.CompareTag("bedonbed")) {
        }
    }

    GameObject FindMatchLimb(GameObject phy) {
        var found = FindObjectsOfType(typeof(LimbBehaviour));
        foreach( var f in found){
            
            var ff = f as LimbBehaviour;
            if (ff.PhysicalBelongToLimb(phy)) { 
                return ff.gameObject;
            }
        }
        return null;
    }


    void OnCollisionEnter(Collision other) {
                var c = transform.parent.GetComponent<CatBasicAIBehaviour>();
        //if (other.rigidbody.velocity.sqrMagnitude < I) return;
        if (other.gameObject.CompareTag("physical") == false) return;
        //Debug.Log("catbody oncollsisionenter");
        //Debug.Log(other.rigidbody.velocity.sqrMagnitude);
        //Debug.Log(other.gameObject.name + "COLLISION");

        if (c.Dead) { return; }

        var limb = FindMatchLimb(other.gameObject);
        if (limb) {
            if (limb.GetComponent<LimbBehaviour>().IsOnHitWindow()) {
                //Debug.Log("defended");
                c.Dead = true;
                GetComponent<Animator>().enabled = false;
                GetComponent<Rigidbody>().isKinematic = false;
                GetComponent<Rigidbody>().useGravity = true;
                FindObjectOfType<CatHitScript>().PlayHitScript();
            }
        }
    }

}
