using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

[ExecuteInEditMode]
public class DynamicUIGrid : MonoBehaviour
{
	private int m_activeChildCount
	{
		get
		{
			int num = 0;
			for (int i = 0; i < base.transform.childCount; i++)
			{
				Transform child = base.transform.GetChild(i);
				if (child.gameObject.activeSelf)
				{
					num++;
				}
			}
			return num;
		}
	}

	private Vector3 sortAxis
	{
		get
		{
			return DynamicUIGrid.GetSortAxis(this.m_SortType);
		}
	}

	private void Update()
	{
		this.Reposition();
	}

	public void UpdateChildUI()
	{
		this.m_ChildWidgetPair.Clear();
		for (int i = 0; i < base.transform.childCount; i++)
		{
			Transform child = base.transform.GetChild(i);
			if (child.gameObject.activeSelf)
			{
				UIWidget component = child.GetComponent<UIWidget>();
				if (component)
				{
					this.m_ChildWidgetPair.Add(child, component);
				}
			}
		}
	}

	public void Reposition()
	{
		Vector3 a = Vector3.zero;
		for (int i = 0; i < this.m_ChildWidgetPair.Count; i++)
		{
			Transform transform = this.m_ChildWidgetPair.Keys.ElementAt(i);
			float num = 0f;
			float num2 = 0f;
			if (i != 0)
			{
				if (this.m_SortType == DynamicUIGrid.SortAxisType.Up || this.m_SortType == DynamicUIGrid.SortAxisType.Down)
				{
					num = (float)this.m_ChildWidgetPair[transform].height;
					num2 = this.m_VerticalSpace;
				}
				else
				{
					num = (float)this.m_ChildWidgetPair[transform].width;
					num2 = this.m_HorizontalSpace;
				}
			}
			transform.localPosition = a + this.sortAxis * (num + num2);
			a = transform.localPosition;
		}
		if (this.m_ChildInverse)
		{
			this.ChildPosInverse();
		}
	}

	private void ChildPosInverse()
	{
		List<Transform> list = this.m_ChildWidgetPair.Keys.ToList<Transform>();
		int count = list.Count;
		for (int i = 0; i < list.Count / 2; i++)
		{
			Transform transform = list[i];
			int num = count - (1 + i);
			if (num >= 0)
			{
				Transform transform2 = list[num];
				Vector3 localPosition = transform.localPosition;
				transform.localPosition = transform2.localPosition;
				transform2.localPosition = localPosition;
			}
		}
	}

	public static Vector3 GetSortAxis(DynamicUIGrid.SortAxisType sort_type)
	{
		switch (sort_type)
		{
		case DynamicUIGrid.SortAxisType.Up:
			return Vector3.up;
		case DynamicUIGrid.SortAxisType.Down:
			return Vector3.down;
		case DynamicUIGrid.SortAxisType.Left:
			return Vector3.left;
		default:
			return Vector3.right;
		}
	}

	[SerializeField]
	[Header("UIの配置方向")]
	private DynamicUIGrid.SortAxisType m_SortType;

	[SerializeField]
	[Header("配置時に空ける横のスペース")]
	private float m_HorizontalSpace;

	[SerializeField]
	[Header("配置時に空ける縦のスペース")]
	private float m_VerticalSpace;

	[SerializeField]
	[Header("子の位置を反転させるか")]
	private bool m_ChildInverse;

	private Dictionary<Transform, UIWidget> m_ChildWidgetPair = new Dictionary<Transform, UIWidget>();

	public enum SortAxisType
	{
		Up,
		Down,
		Left,
		Right
	}
}
