using UnityEngine;
using System.Collections;

public class ElementalSpawner : MonoBehavclops
{

	public GameObject spherePrefab;
	public EnergyWell soulWell;
	public EnergyWell plasmaWell;
	public EnergyWell mercuryWell;
	public float sphereFillRate = 0.3f;
	public float wellEmptyRate = 0.3f;
	public InfintyQueue infinityQueue;

	private ElementalSphere _currentSphere;

	public void Start()
	{
		soulWell.Element = Element.Soul;
		plasmaWell.Element = Element.Plasma;
		mercuryWell.Element = Element.Mercury;
	}

	public void OnEnable()
	{
		soulWell.OnTapDown += EnergyWellTapDown;
		plasmaWell.OnTapDown += EnergyWellTapDown;
		mercuryWell.OnTapDown += EnergyWellTapDown;
		soulWell.OnTapHold += EnergyWellTapHold;
		plasmaWell.OnTapHold += EnergyWellTapHold;
		mercuryWell.OnTapHold += EnergyWellTapHold;
	}

	public void OnDisable()
	{
		soulWell.OnTapDown -= EnergyWellTapDown;
		plasmaWell.OnTapDown -= EnergyWellTapDown;
		mercuryWell.OnTapDown -= EnergyWellTapDown;
		soulWell.OnTapHold -= EnergyWellTapHold;
		plasmaWell.OnTapHold -= EnergyWellTapHold;
		mercuryWell.OnTapHold -= EnergyWellTapHold;
	}

	public void EnergyWellTapDown(EnergyWell well)
	{
		if (_currentSphere == null) CreateSphere(well.Element);
	}

	public void EnergyWellTapHold(EnergyWell well)
	{
		if (_currentSphere == null) return;
		if (_currentSphere.Energy >= 1f) return;
		// if (well.Energy - wellEmptyRate * Time.deltaTime <= 0f) return;
		_currentSphere.Element = _currentSphere.Element.AddElement(well.Element);
		_currentSphere.Energy += sphereFillRate * Time.deltaTime;
		well.Energy -= wellEmptyRate * Time.deltaTime;
	}

	public void SphereWasPickedUp(ElementalSphere sphere)
	{
		infinityQueue.SphereWasPickedUp(_currentSphere);
		_currentSphere.WasPickedUp -= SphereWasPickedUp;
		_currentSphere = null;
	}

	private void CreateSphere(Element element)
	{
		var obj = Instantiate(spherePrefab, Cached<Transform>().position, Quaternion.identity) as GameObject;
		var pos = obj.transform.localPosition;
		pos.z += -1f;
		obj.transform.localPosition = pos;
		_currentSphere = obj.GetComponent<ElementalSphere>();
		_currentSphere.Element = element;
		_currentSphere.WasPickedUp += SphereWasPickedUp;
	}
}
