using System;
using UnityEngine;
using Holoville.HOTween;
using com.deeperbeige.lib;

namespace com.deeperbeige.pipiee
{
	public class ButtonAnim : MonoBehaviour
	{
	    private Vector3 idleScale;
	    private Vector3 pressedScale;
		private Vector3 idlePos;
		private Vector3 pressedPos;
		
		private float animInSeconds      = 0.10f;
		private float animOutSeconds     = 0.25f;
		private float pressedScaleFactor = 1.25f;

		private bool initialised = false;
		
		[System.NonSerialized]
		public bool disabled = false;
		
		private void Init()
		{
			if (initialised) return;
			initialised = true;
			
			// Settings for normal buttons with central registration points
			idleScale    = transform.localScale;
			pressedScale = transform.localScale * pressedScaleFactor;
			idlePos      = transform.localPosition;
			pressedPos   = transform.localPosition;
			
			// Calculate settings for special buttons with non-central registration points
			GameObject scaleGO = GameObjects.FindNested(gameObject, "ScaleCentre", true);
			if (scaleGO != null)
			{
				Vector3 pressedOffset = pressedScaleFactor * Coords.getLocal(transform, scaleGO.transform);
				Vector3 worldOffset   = scaleGO.transform.TransformPoint(pressedOffset);
				pressedPos            = transform.parent.InverseTransformPoint(worldOffset);
			}
	    }
		
		private void OnClick()
		{
			Init();
			
			if (disabled) return;
			
			HOTween.Kill(transform);
			transform.localScale    = idleScale;
			transform.localPosition = idlePos;
			HOTween.To(transform, animInSeconds, new TweenParms()
				.Prop("localScale",    pressedScale)
				.Prop("localPosition", pressedPos)
				.Ease(EaseType.EaseOutCubic)
			);
			HOTween.To(transform, animOutSeconds, new TweenParms()
				.Prop("localScale",    idleScale)
				.Prop("localPosition", idlePos)
				.Delay(animInSeconds)
				.Ease(EaseType.EaseInCubic)
			);
		}
	}
}
