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

public class RagDollHandler : MonoBehaviour {

    private Component[] m_colliders;
    private Component[] m_rigidbodies;

    private Rigidbody2D m_myRigidbody2D;

    public bool playerIsDead;

    void OnEnable ()
    {
        GetCollider();
        SetRigidBodies(false);

        m_myRigidbody2D = transform.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (!m_myRigidbody2D.simulated)
            m_myRigidbody2D.simulated = true;
    }

    public void GetCollider ()
    {
        m_colliders = GetComponentsInChildren<Collider2D>();

        foreach (Collider2D collider in m_colliders)
        {
            if(collider.gameObject.GetComponent<RagdollCollision>() == null)
            {
                collider.gameObject.AddComponent<RagdollCollision>();
                collider.gameObject.GetComponent<RagdollCollision>().SetMyRagdollHandler(gameObject.GetComponent<RagDollHandler>());
            }
        }
    }

    public void SetRigidBodies (bool simulate)
    {
        m_rigidbodies = GetComponentsInChildren<Rigidbody2D>();

        foreach (Rigidbody2D rig in m_rigidbodies)
        {
            rig.simulated = simulate;
            rig.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
        }
    }

    public void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.layer != LayerMask.NameToLayer("Floor") && col.gameObject.layer != LayerMask.NameToLayer("Player1") && col.gameObject.layer != LayerMask.NameToLayer("Player2"))
            SetRigidBodies(true);
    }
}
