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

namespace JLGames.RocketDriver.Actions.Layer
{
    public class LayerConfig : MonoBehaviour
    {
        [Serializable]
        public struct LayerInfo
        {
            public string Name;
            public int Priority;
        }

        [SerializeField] private List<LayerInfo> m_Layers = new List<LayerInfo>
        {
            new LayerInfo {Name = LayerNames.LayerBackGround, Priority = 0},
            new LayerInfo {Name = LayerNames.LayerSceneView, Priority = 5},
            new LayerInfo {Name = LayerNames.LayerMsgCenter, Priority = 10},
            new LayerInfo {Name = LayerNames.LayerUI, Priority = 15},
            new LayerInfo {Name = LayerNames.LayerWindow, Priority = 20},
            new LayerInfo {Name = LayerNames.LayerMsgTop, Priority = 25},
            new LayerInfo {Name = LayerNames.LayerTips, Priority = 30},
            new LayerInfo {Name = LayerNames.LayerTop, Priority = 35},
        };

        public LayerInfo[] GetSortedLayers(bool asc = true)
        {
            if (asc)
                SortLayersAsc();
            else
                SortLayersDesc();
            return m_Layers.ToArray();
        }

        public string[] GetSortedLayerNames(bool asc = true)
        {
            if (asc)
                SortLayersAsc();
            else
                SortLayersDesc();

            var rs = new string[m_Layers.Count];
            for (var i = 0; i < rs.Length; i++)
            {
                rs[i] = m_Layers[i].Name;
            }

            return rs;
        }

        public bool AddLayer(string layerName, int priority, bool supportDuplication = true)
        {
            if (!supportDuplication)
            {
                foreach (var layer in m_Layers)
                {
                    if (layer.Name == layerName)
                    {
                        return false;
                    }
                }
            }

            var newLi = new LayerInfo
            {
                Name = layerName,
                Priority = priority
            };
            m_Layers.Add(newLi);
            return true;
        }

        // --------------------------------------

        private void SortLayersAsc()
        {
            m_Layers.Sort((x, y) => x.Priority.CompareTo(y.Priority));
        }

        private void SortLayersDesc()
        {
            m_Layers.Sort((x, y) => -x.Priority.CompareTo(y.Priority));
        }
    }
}