using UnityEngine;

namespace Wizard;

public class UIMarquee : MonoBehaviour
{
	private enum State
	{
		Stop,
		WaitForMove,
		Move,
		Reappear
	}

	[SerializeField]
	[Range(0f, float.MaxValue)]
	private float _secToStartMoving = 1.5f;

	[SerializeField]
	[Range(0f, float.MaxValue)]
	private float _movePerSec = 100f;

	[SerializeField]
	[Range(0f, float.MaxValue)]
	private float _secToReappear = 1.5f;

	[SerializeField]
	private AnimationCurve _reappearCurve = AnimationCurve.Linear(0f, 0f, 1f, 1f);

	[SerializeField]
	[Range(0f, float.MaxValue)]
	private float _widthOfNeedsToScroll = 256f;

	[SerializeField]
	private UIPanel _panel;

	[SerializeField]
	private UIWidget _content;

	private State _state;

	private float _timeCount;

	private float _startX;

	public void StartMarquee()
	{
		if ((float)_content.width < _widthOfNeedsToScroll)
		{
			SetState(State.Stop);
		}
		else
		{
			SetState(State.WaitForMove);
		}
	}

	public void Reset()
	{
		SetState(State.Stop);
		SetAlpha(1f);
	}

	public void SetWidthOfNeedsToScroll(float width)
	{
		_widthOfNeedsToScroll = width;
	}

	public void SetDefaultWidthOfNeedsToScroll()
	{
		_widthOfNeedsToScroll = _panel.width;
	}

	private void Update()
	{
		_timeCount += Time.deltaTime;
		switch (_state)
		{
		case State.WaitForMove:
			if (_timeCount >= _secToStartMoving)
			{
				SetState(State.Move);
			}
			break;
		case State.Move:
			if (IsScrollComplete())
			{
				SetState(State.Reappear);
				SetAlpha(0f);
			}
			else
			{
				SetContentPosX(_startX - _movePerSec * _timeCount);
			}
			break;
		case State.Reappear:
			SetAlpha(_reappearCurve.Evaluate(_timeCount / _secToReappear));
			if (_timeCount >= _secToReappear)
			{
				SetState(State.WaitForMove);
				SetAlpha(1f);
			}
			break;
		}
	}

	private void SetState(State state)
	{
		_state = state;
		_timeCount = 0f;
		_panel.UpdateAnchors();
		_content.UpdateAnchors();
		_startX = CalcStartX();
		SetContentPosX(_startX);
	}

	private float CalcStartX()
	{
		return _panel.baseClipRegion.x - _panel.baseClipRegion.z * 0.5f;
	}

	private void SetContentPosX(float posX)
	{
		Transform obj = _content.transform;
		Vector3 localPosition = obj.localPosition;
		localPosition.x = posX;
		obj.localPosition = localPosition;
	}

	private bool IsScrollComplete()
	{
		return _content.transform.localPosition.x - _startX <= (float)(-_content.width);
	}

	private void SetAlpha(float alpha)
	{
		_panel.alpha = alpha;
	}
}
