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

public abstract class LevelObjectBase : MonoBehaviour
{
    public abstract LevelObjectFaction ObjectFaction { get; }
    public abstract LevelObjectType ObjectType { get; }


    public int MaxHP;
    public int StartingHP;
    public int CurrentHP;
    public float DestroyDelay = 1;
    public bool Destroyed;
    protected bool Destroying = false;


    protected List<LevelObjectBase> ContactObjects;

    protected bool paused = false;

    public virtual void TakeDamage(LevelObjectBase source, int dmg)
    {
        CurrentHP -= dmg;
        if (CurrentHP <= 0)
        {
            HPZero();
        }
    }
    protected abstract void HPZero();
    public virtual void Init()
    {
        ContactObjects = new List<LevelObjectBase>();
        EventManager.SubscribeGamePaused(Pause);
        EventManager.SubscribeGameResumed(Resume);
        EventManager.SubscribeObjectDestroyed(RemoveLevelObjectRef);
        CurrentHP = StartingHP;
    }
    protected virtual void TearDown()
    {
        ContactObjects.Clear();
        EventManager.UnsubscribeGamePaused(Pause);
        EventManager.UnsubscribeGameResumed(Resume);
        EventManager.UnsubscribeObjectDestroyed(RemoveLevelObjectRef);
    }

    protected virtual void Kill()
    {
        if (!Destroying)
        {
            gameObject.SetActive(false);
            Destroying = true;
            TearDown();
            EventManager.TriggerObjectDestroyed(this);
            Destroy(this.gameObject, DestroyDelay);
        }
    }

    protected void Pause()
    {
        paused = true;
    }

    protected void Resume()
    {
        paused = false;
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.Log($"{this.name}: collider entered target={collision.name}");
        var levelObject = collision.GetComponent<LevelObjectBase>();
        if (levelObject != null && !ContactObjects.Contains(levelObject))
        {
            ContactObjects.Add(levelObject);
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        Debug.Log($"{this.name}: collider exited target={collision.name}");
        var levelObject = collision.GetComponent<LevelObjectBase>();
        RemoveLevelObjectRef(levelObject);
    }

    protected virtual void RemoveLevelObjectRef(LevelObjectBase obj)
    {
        if (obj != null && ContactObjects.Contains(obj))
        {
            ContactObjects.Remove(obj);
        }

    }

}

public enum LevelObjectType
{
    Unknown = 0,
    Player,
    Tower,
    Wall,
    Knight,
    Zombie,
    GraveStone,
}
public enum LevelObjectFaction
{
    Unknown = 0,
    Human,
    Zombie,
}
