﻿using System;
using System.Collections.Generic;
using JLGames.RocketDriver.Actions.AssetIndex;
using JLGames.RocketDriver.Actions.Loaderx;
using JLGames.RocketDriver.Actions.Utils;
using JLGames.RocketDriver.CSharp.Service;
using UnityEngine;

namespace JLGames.RocketDriver.Games.Service.DataConfig
{
    public abstract class AbstractConfigDataService : ServiceBase, IInitService, IProgressingService,
        IConfigDataService
    {
        private readonly Dictionary<string, string> m_MapContext = new Dictionary<string, string>();
        private BundleRef m_Bundle;

        protected string m_BundleName = "cfg";
        protected string m_AssetListName = "Cfg/cfg.asset";

        // IConfigDataService

        public string ExtractJsonContext(string fileName)
        {
            if (!m_MapContext.ContainsKey(fileName))
            {
                return null;
            }

            var rs = m_MapContext[fileName];
            m_MapContext.Remove(fileName);
            return rs;
        }

        // IService

        public override void Clear()
        {
            m_MapContext.Clear();
            if (null != m_Bundle)
            {
                m_Bundle.Release();
                m_Bundle = null;
            }

            base.Clear();
        }

        // IInitService

        public virtual void Init()
        {
            Loader.LoadBundleAsync(m_BundleName, (abRef, suc) =>
            {
                if (!suc)
                {
                    throw new Exception("数据加载错误");
                }

                DebugUtil.Log("下载cfg完成：", abRef.BundleName);
                m_Bundle = abRef;
                InitCfgInfo();
                HandleData();
            }, false);
        }

        private int m_Size;
        private int m_Index;
        private DirFilesIndex m_IndexInfo;

        private void InitCfgInfo()
        {
            m_IndexInfo = Loader.LoadAssetSync<DirFilesIndex>(m_AssetListName, m_Bundle.Bundle);
            m_Size = m_IndexInfo.Size;
            m_Index = 0;
            DebugUtil.Log("CfgInfo:", m_Size);
        }

        private void HandleData()
        {
            if (m_Index >= m_Size)
            {
                m_Bundle.Release();
                m_Bundle = null;
                InvokeInited();
                return;
            }

            CacheContext(m_IndexInfo[m_Index]);
            m_Index++;
            InvokdProcessing(HandleData);
        }

        private void CacheContext(NamePathInfo info)
        {
            var textAsset = Loader.LoadAssetSync<TextAsset>(info.Path, m_Bundle.Bundle);
            if (null == textAsset)
            {
                return;
            }

            m_MapContext[info.Name] = textAsset.text;
        }
    }
}