using UnityEngine;
using System;
using System.Collections;

public class EnergyWell : MonoBehavclops
{

	public event Action<EnergyWell> OnTapDown;
	public event Action<EnergyWell> OnTapHold;
	public event Action<EnergyWell> OnTapUp;

	public float rechargeRate = 0.02f;

	private bool _isHoldingTap;
	private Vector3 _startScale;
	private Vector3 _startPos;

	private Element _element = Element.Void;
	public Element Element
	{
		get { return _element; }
		set 
		{ 
			_element = value; 
			// LayoutForElement();
		}
	}

	private float _energy;
	public float Energy
	{
		get { return _energy; }
		set 
		{ 
			if (value <= 0f) StopTap();
			_energy = Mathf.Clamp(value, 0f, 1f);
			LayoutForEnergy();
		}
	}

	public void Awake()
	{
		_startScale = Cached<Transform>().localScale;
		_startPos = Cached<Transform>().localPosition;
	}

	public void Start()
	{
		Energy = 1f;
	}

	private void LayoutForElement()
	{
		Cached<SpriteRenderer>().color = Element.Color;
	}

	private void LayoutForEnergy()
	{
		var newScale = _startScale;
		newScale.y *= _energy;
		// Cached<Transform>().localScale = newScale;
		var newPos = _startPos;
		newPos.y -= (1f - _energy) * (Cached<SpriteRenderer>().sprite.bounds.size.y * 0.9f);
		Cached<Transform>().localPosition = newPos;
	}

	public void OnMouseDown()
	{
		_isHoldingTap = true;
		if (OnTapDown != null) OnTapDown(this);
	}

	public void OnMouseExit()
	{
		// StopTap();
	}

	public void OnMouseUp()
	{
		StopTap();
	}

	private void StopTap()
	{
		if (!_isHoldingTap) return;
		_isHoldingTap = false;
		if (OnTapUp != null) OnTapUp(this);
	}

	public void Update()
	{
		Energy += rechargeRate * Time.deltaTime;
		if (_isHoldingTap) {
			if (OnTapHold != null) OnTapHold(this);
		}
	}

}
