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

namespace TyphoonUI
{
    /// <summary>
    /// 多边形按钮
    /// </summary>
    [RequireComponent(typeof(PolygonButtonImage))]
    public class PolyImageButton : Button
    {
        private Graphic[] m_graphics;

        protected Graphic[] Graphics
        {
            get
            {
                List<Graphic> graphics = transform.GetComponentsInChildren<Graphic>().ToList();
                for (int i = graphics.Count - 1; i >= 0; i--)
                {
                    //移除PloygonButtonImage部分
                    if ((graphics[i] as PolygonButtonImage) != null)
                    {
                        graphics.RemoveAt(i);
                    }
                }

                m_graphics = graphics.ToArray();
                return m_graphics;
            }
        }

        protected override void DoStateTransition(SelectionState state, bool instant)
        {
            Color color;
            switch (state)
            {
                case SelectionState.Normal:
                    color = this.colors.normalColor;
                    break;
                case SelectionState.Highlighted:
                    color = this.colors.highlightedColor;
                    break;
                case SelectionState.Pressed:
                    color = this.colors.pressedColor;
                    break;
                case SelectionState.Disabled:
                    color = this.colors.disabledColor;
                    break;
                default:
                    color = Color.black;
                    break;
            }

            if (base.gameObject.activeInHierarchy)
            {
                switch (this.transition)
                {
                    case Transition.ColorTint:
                        ColorTween(color * this.colors.colorMultiplier, instant);
                        break;
                    default:
                        throw new NotSupportedException();
                }
            }
        }

        private void ColorTween(Color targetColor, bool instant)
        {
            if (this.targetGraphic == null)
            {
                return;
            }

            foreach (Graphic g in this.Graphics)
            {
                g.CrossFadeColor(targetColor, (!instant) ? this.colors.fadeDuration : 0f, true, true);
            }
        }
    }
}