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

public class MonsterFactory : MonoBehaviour
{
    public GameObject[] MonsterPrefabs = null;
    public GameObject MonsterHealthbarPrefab = null;
    public GameObject MonsterSwingTimerPrefab = null;
    public Transform UIParent = null;

    public Transform[] MonsterAnchors = null;

    public GameObject CreateMonster(int index)
    {
        // Gain 50 points per monster spawned
        PlayerStats.Score += 50;

        MonsterStats[] monsters = FindObjectsOfType<MonsterStats>();
        if (monsters.Length >= MonsterAnchors.Length)
            return null; // No room for more monsters

        int AnchorIndex = 0;
        for (AnchorIndex = 0; AnchorIndex < MonsterAnchors.Length; AnchorIndex++)
        {
            bool CloseMonsterFound = false;
            // Check the monsters to see if any of them are close to this anchor
            foreach(MonsterStats monster in monsters)
            {
                if ((monster.transform.position - MonsterAnchors[AnchorIndex].position).sqrMagnitude < 0.5f)
                {
                    CloseMonsterFound = true;
                    break;
                }
            }

            if (!CloseMonsterFound)
                break;
        }


        GameObject goMonster = GameObject.Instantiate(MonsterPrefabs[index], MonsterAnchors[AnchorIndex].position, MonsterAnchors[AnchorIndex].rotation) as GameObject;

        if (goMonster.GetComponent<HealthComponent>())
        {
            GameObject goHealthbar = GameObject.Instantiate(MonsterHealthbarPrefab, UIParent) as GameObject;
            goHealthbar.GetComponent<HealthbarBinding>().Target = goMonster.GetComponent<HealthComponent>();
        }

        if (goMonster.GetComponent<SwingTimerComponent>())
        {
            GameObject goSwingTimer = GameObject.Instantiate(MonsterSwingTimerPrefab, UIParent) as GameObject;
            goSwingTimer.GetComponent<SwingTimerBinding>().SwingTimer = goMonster.GetComponent<SwingTimerComponent>();
        }

        return goMonster;
    }

    public void HealthComponentDied(HealthComponent hc)
    {
        Team team = hc.GetComponent<Team>();
        if (team != null && team.team == TeamValue.Enemy)
        {
            // Clean up any stray health components and swing timer components
            HealthbarBinding[] healthBindings = FindObjectsOfType<HealthbarBinding>();
            foreach(HealthbarBinding hbb in healthBindings)
            {
                if (hbb.Target == hc)
                    Object.Destroy(hbb.gameObject);
            }

            SwingTimerBinding[] swingBindings = FindObjectsOfType<SwingTimerBinding>();
            foreach (SwingTimerBinding stb in swingBindings)
            {
                if (stb.SwingTimer.gameObject == hc.gameObject)
                    Object.Destroy(stb.gameObject);
            }
        }

    }
}
