﻿using System;
using System.Collections.Generic;

namespace JLGames.RocketDriver.Actions.ExcelExporter
{
    public class GroupCfgTitle<TExtCfgTitle, TCfgTitle> where TExtCfgTitle : ExtCfgTitle<TCfgTitle>, new()
    {
        private readonly List<TExtCfgTitle> m_Temp = new List<TExtCfgTitle>();
        protected readonly List<TExtCfgTitle> m_DataList = new List<TExtCfgTitle>();

        public TExtCfgTitle[] DataArray => m_DataList.ToArray();
        public int GroupSize => m_DataList.Count;
        public TExtCfgTitle GetByIndex(int index)
        {
            if (null == m_DataList || GroupSize == 0 || index >= GroupSize) return default(TExtCfgTitle);
            return m_DataList[index];
        }

        public TExtCfgTitle GetById(int id)
        {
            if (null == m_DataList || m_DataList.Count == 0) return default(TExtCfgTitle);
            for (var i = 0; i < m_DataList.Count; i++)
            {
                if (m_DataList[i].Id == id)
                {
                    return m_DataList[i];
                }
            }

            return default(TExtCfgTitle);
        }

        public TExtCfgTitle GetData(Predicate<TExtCfgTitle> match)
        {
            return m_DataList.Find(match);
        }

        public TExtCfgTitle[] GetAllData(Predicate<TExtCfgTitle> match)
        {
            if (null == m_DataList || m_DataList.Count == 0) return null;
            m_Temp.Clear();
            foreach (var userTask in m_DataList)
            {
                if (match(userTask))
                {
                    m_Temp.Add(userTask);
                }
            }

            return m_Temp.ToArray();
        }

        public void SetData(string jsonContext, string idName = "Id")
        {
            var arr = DataParsingUtil.ParseConfigArray<TCfgTitle>(jsonContext);

            var rawDataList = arr;
            var data = new TExtCfgTitle[rawDataList.Length];
            for (var i = 0; i < data.Length; i++)
            {
                data[i] = new TExtCfgTitle();
                data[i].SetData(rawDataList[i], idName);
            }

            SetData(data);
        }

        public void SetData(TExtCfgTitle[] unitArray)
        {
            Reset();
            m_DataList.AddRange(unitArray);
            HandleDataGroup();
        }

        public void Reset()
        {
            m_Temp.Clear();
            m_DataList.Clear();
        }

        protected virtual void HandleDataGroup()
        {
        }
    }
}