using UnityEngine;
using System.Collections;
using Framework.Entities;
using Framework.Utility;
using Framework.StatSystem;
using Framework.Extensions;

public class AlchemistDestroyAbility : CoreBehaviour
{
    public class AddMarkAction : CoreAction
    {
    }

    public class RemoveMarkAction : CoreAction
    {
    }

    bool usedToday = false;
    public int marks = 0; 
    private AlchemistBag bag;

    public void UseDestroy()
    {
        //if (this.marks == 0 && this.bag.destroyCount > 0)
        //{
        //    ExplosionBehaviour explosion = ((GameObject)Instantiate(Resources.Load("DestroyField"), this.transform.position, new Quaternion())).GetComponent<ExplosionBehaviour>();
        //    explosion.creator = this.gameObject;
        //    this.bag.destroyCount--;
        //}

        if (this.bag.destroyCount > 0 && usedToday == false)
        {
            float minDistance = float.MaxValue;
            GameObject closest = null;
            Collider[] hitColliders = Physics.OverlapSphere(this.transform.position, 2f);
            for (int i = 0; i < hitColliders.Length; i++)
            {
                if (hitColliders[i].GetComponent<PersonResponsive>() != null
                    && Vector3.Distance(this.transform.position, hitColliders[i].transform.position) < minDistance)
                {
                    closest = hitColliders[i].gameObject;
                }
            }
            if (closest != null)
            {
                closest.Interact(new PersonResponsive.MarkForDeathAction());
                this.bag.destroyCount--;
                usedToday = true;
            }
        }
    }

    protected override void InnerAwake()
    {
        AddActionHandler<AddMarkAction>(AddMark);
        AddActionHandler<RemoveMarkAction>(RemoveMark);
        AddGlobalActionHandler<DayDirector.NewDayAction>(this, (DayDirector.NewDayAction action) => { usedToday = false; });
        this.bag = GetComponent<AlchemistBag>();
    }

    protected override void InnerUpdate()
    {
    }

    private void AddMark(AddMarkAction action)
    {
        this.marks++;
        //Debug.Log("Add marks, now: " + this.marks);
    }

    private void RemoveMark(RemoveMarkAction action)
    {
        this.marks--;
        if (this.marks < 0)
        {
            this.marks = 0;
        }
        //Debug.Log("Remove marks, now: " + this.marks);
    }
}
