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

public class EnemyManager : MonoBehaviour
{
    public float health = 100;
    public float damage = 10;
    public float attackRate = 2;
    private float attackTime = 2;
    public float actualHealth;
    private NavMeshAgent navMeshAgent;
    private PlayerManager player;
    public BarricadeManager barricadeManager;
    public List<GameObject> bodyParts = new List<GameObject>();

    // Start is called before the first frame update
    void Start()
    {
        attackTime = attackRate;
        actualHealth = health;
        player = FindObjectOfType<PlayerManager>();
        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        DropBodyPart();
        if (actualHealth <= 0)
        {
            Destroy(transform.gameObject, 0.1f);
        }
        DestroyBarricades();
        Attack();

        if (navMeshAgent != null && barricadeManager == null)
        {
            navMeshAgent.SetDestination(player.transform.position);
        }
        else if (navMeshAgent != null && barricadeManager != null)
        {
            navMeshAgent.SetDestination(new Vector3(barricadeManager.walkPoint.position.x, 0, barricadeManager.walkPoint.position.z));
        }
    }

    void FixedUpdate()
    {
        if (navMeshAgent.pathStatus == NavMeshPathStatus.PathComplete)
        {
            if (actualHealth > 0 && barricadeManager == null)
            {
                Vector3 _dir = player.transform.position - transform.position;
                _dir.Normalize();
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(_dir), 5 * Time.deltaTime);
            }
            else if (actualHealth > 0 && barricadeManager != null)
            {
                Vector3 _dir = barricadeManager.transform.position - transform.position;
                _dir.Normalize();
                transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(_dir), 5 * Time.deltaTime);
            }
        }
    }

    public void Damage()
    {
        WeaponManager weaponManager = player.weaponList[player.selectedWeapon].GetComponent<WeaponManager>();
        if (weaponManager != null) {
            actualHealth -= weaponManager.damage;
        }
    }

    void DestroyBarricades()
    {
        NavMeshPath path = new NavMeshPath();
        if (navMeshAgent != null) {
            navMeshAgent.CalculatePath(player.transform.position, path);
            if (path.status == NavMeshPathStatus.PathPartial)
            {
                BarricadeManager[] barricadeManagers = GameObject.FindObjectsOfType<BarricadeManager>();
                foreach (BarricadeManager localBarricadeManager in barricadeManagers)
                {
                    if (barricadeManager == null)
                    {
                        barricadeManager = localBarricadeManager;
                    }
                    else
                    {
                        if (localBarricadeManager.health < barricadeManager.health || Vector3.Distance(barricadeManager.transform.position, transform.position) > Vector3.Distance(localBarricadeManager.transform.position, transform.position)) {
                            barricadeManager = localBarricadeManager;
                        }
                    }
                }
            }
            else
            {
                barricadeManager = null;
            }
        }
    }

    void DropBodyPart()
    {
        if (bodyParts.Count > 0)
        {
            float number = health / bodyParts.Count;
            for (int i = 0; i < bodyParts.Count; i++)
            {
                if (bodyParts.Count - 1 != i)
                {
                    if ((health - actualHealth) / number > i)
                    {
                        if (bodyParts[i] != null && bodyParts[i].transform.parent != null)
                        {
                            bodyParts[i].transform.parent = null;
                            bodyParts[i].AddComponent<Rigidbody>();
                            Rigidbody rigidBodyEnemy = bodyParts[i].GetComponent<Rigidbody>() as Rigidbody;
                            bodyParts[i].AddComponent<MeshCollider>();
                            MeshCollider meshCollider = bodyParts[i].GetComponent<MeshCollider>() as MeshCollider;
                            meshCollider.convex = true;
                            rigidBodyEnemy.mass = 10 * bodyParts.Count;
                            Destroy(bodyParts[i], 4);
                        }
                    }
                }
                else
                {
                    if (actualHealth == 0)
                    {
                        if (bodyParts[i] != null && bodyParts[i].transform.parent != null)
                        {
                            bodyParts[i].transform.parent = null;
                            bodyParts[i].AddComponent<Rigidbody>();
                            Rigidbody rigidBodyEnemy = bodyParts[i].GetComponent<Rigidbody>() as Rigidbody;
                            bodyParts[i].AddComponent<MeshCollider>();
                            MeshCollider meshCollider = bodyParts[i].GetComponent<MeshCollider>() as MeshCollider;
                            meshCollider.convex = true;
                            navMeshAgent.isStopped = true;
                            navMeshAgent.enabled = false;
                            navMeshAgent = null;
                            rigidBodyEnemy.velocity = bodyParts[i].transform.forward;
                            rigidBodyEnemy.mass = 10 * bodyParts.Count;
                            Destroy(bodyParts[i], 4);
                        }
                    }
                }
            }
        }
    }

    void Attack()
    {
        RaycastHit hit;
        if (Physics.Raycast(transform.position + new Vector3(0,0.5f,0),transform.forward,out hit,2) && attackTime <= Time.time)
        {
            if (hit.transform.CompareTag("Player"))
            {
                player.Damage(damage);
                attackTime = attackRate + Time.time;
            }
            if (hit.transform.CompareTag("BarricadeField"))
            {
                BarricadeManager barricadeManager = hit.transform.GetComponent<BarricadeManager>();
                if (barricadeManager != null)
                {
                    barricadeManager.Damage(damage);
                    attackTime = attackRate + Time.time;
                }
            }
        }
    }

    private void OnParticleCollision(GameObject other)
    {
        if (other.transform.tag == "Bullets")
        {
            Damage();
        }
    }

    void OnTriggerEnter(Collider collider)
    {
        if (collider.transform.CompareTag("Meele"))
        {
            Damage();
            
        }
    }
}
