using UnityEngine;

namespace Wizard;

public class CenteringUIWidget : MonoBehaviour
{
	[SerializeField]
	private Transform _offset;

	[SerializeField]
	private bool _isCenteringHorizontal = true;

	[SerializeField]
	private bool _isCenteringVertical;

	public void Reposition()
	{
		if (_offset == null || (!_isCenteringHorizontal && !_isCenteringVertical))
		{
			return;
		}
		UIWidget[] componentsInChildren = _offset.GetComponentsInChildren<UIWidget>();
		if (componentsInChildren.Length != 0)
		{
			_offset.localPosition = Vector3.zero;
			Bounds bounds = GetBounds(componentsInChildren[0], _offset);
			for (int i = 1; i < componentsInChildren.Length; i++)
			{
				bounds.Encapsulate(GetBounds(componentsInChildren[i], _offset));
			}
			Vector3 localPosition = _offset.localPosition;
			if (_isCenteringHorizontal)
			{
				localPosition.x = 0f - bounds.center.x;
			}
			if (_isCenteringVertical)
			{
				localPosition.y = 0f - bounds.center.y;
			}
			_offset.localPosition = localPosition;
		}
	}

	private static Bounds GetBounds(UIWidget widget, Transform parent)
	{
		if (!(widget is UILabel))
		{
			return widget.CalculateBounds(parent);
		}
		UILabel uILabel = (UILabel)widget;
		NGUIText.Alignment alignment = uILabel.alignment;
		if (alignment == NGUIText.Alignment.Automatic)
		{
			switch (uILabel.pivot)
			{
			case UIWidget.Pivot.TopLeft:
			case UIWidget.Pivot.Left:
			case UIWidget.Pivot.BottomLeft:
				alignment = NGUIText.Alignment.Left;
				break;
			case UIWidget.Pivot.Top:
			case UIWidget.Pivot.Center:
			case UIWidget.Pivot.Bottom:
				alignment = NGUIText.Alignment.Center;
				break;
			case UIWidget.Pivot.TopRight:
			case UIWidget.Pivot.Right:
			case UIWidget.Pivot.BottomRight:
				alignment = NGUIText.Alignment.Right;
				break;
			}
		}
		Bounds result = uILabel.CalculateBounds(parent);
		Vector3 vector = new Vector3(uILabel.printedSize.x, uILabel.printedSize.y, 0f);
		switch (alignment)
		{
		case NGUIText.Alignment.Left:
			result.max = result.min + vector;
			break;
		case NGUIText.Alignment.Center:
			result.size = vector;
			break;
		case NGUIText.Alignment.Right:
			result.min = result.max - vector;
			break;
		}
		return result;
	}
}
