using UnityEngine;
using System.Collections.Generic;

[AddComponentMenu("Destructible 2D/D2D Fixture")]
public class D2D_Fixture : MonoBehaviour
{
	public static List<D2D_Fixture> Fixtures = new List<D2D_Fixture>();
	
	[D2D_RangeAttribute(0.01f, 1.0f)]
	public float Threshold = 0.5f;
	
	private D2D_Destructible destructible;
	
	private bool dirty = true;
	
	[SerializeField]
	private int fixtureID;
	
	private static int nextFixtureID = 1;
	
	protected virtual void OnSpriteSplit(bool isClone)
	{
		// Assign a fixtureID to the parent, this will be copied to the clones
		if (isClone == false)
		{
			if (nextFixtureID > 1000000)
			{
				nextFixtureID = 1;
			}
			else
			{
				nextFixtureID += 1;
			}
			
			fixtureID = nextFixtureID;
		}
		
		dirty = true;
	}
	
	protected virtual void OnAlphaTexModified()
	{
		dirty = true;
	}
	
	protected virtual void OnEnable()
	{
		Fixtures.Add(this);
	}
	
	protected virtual void OnDisable()
	{
		Fixtures.Remove(this);
	}
	
	protected virtual void Update()
	{
		if (dirty == true)
		{
			dirty        = false;
			destructible = D2D_Helper.GetComponentUpwards<D2D_Destructible>(transform);
			
			if (destructible != null)
			{
				var alpha = destructible.GetAlpha(transform.position);
				
				// Break fixture?
				if (alpha < Threshold)
				{
					DestroyFixture();
				}
				// Break others?
				else if (fixtureID > 0)
				{
					for (var i = Fixtures.Count - 1; i >= 0; i--)
					{
						var fixture = Fixtures[i];
						
						if (fixture != null && fixture != this && fixture.fixtureID == fixtureID)
						{
							fixture.DestroyFixture();
						}
					}
				}
			}
		}
	}
	
	public static D2D_Fixture FindFixture(string name, Transform transform)
	{
		if (transform != null)
		{
			var destructible = transform.GetComponentInParent<D2D_Destructible>();
			
			if (destructible != null)
			{
				var fixtures = destructible.GetComponentsInChildren<D2D_Fixture>();
				
				foreach (var fixture in fixtures)
				{
					if (fixture.name == name)
					{
						return fixture;
					}
				}
			}
		}
		
		return null;
	}
	
	private void DestroyFixture()
	{
		D2D_Helper.Destroy(gameObject);
	}
}