﻿using JLGames.RocketDriver.Actions.Loaderx;
using JLGames.RocketDriver.Actions.Pool;
using JLGames.RocketDriver.Actions.Utils;
using JLGames.RocketDriver.CSharp;
using JLGames.RocketDriver.CSharp.Service;
using JLGames.RocketDriver.Samples.ServiceDemo.Service;
using UnityEngine;

namespace JLGames.RocketDriver.Samples.ServiceDemo
{
    public class ServiceDemo : MonoBehaviour
    {
        [SerializeField] private GameObject m_NodeService;
        [SerializeField] private GameObject m_ButtonStart;
        [SerializeField] private GameObject m_ButtonClear;

        private MetaGameObjectPool m_Pool;

        private void Awake()
        {
            m_Pool = new MetaGameObjectPool(m_NodeService);
            m_Pool.SetContainer(m_NodeService.transform.parent);
        }

        private void Start()
        {
            Loader.InitLoader("ServiceLoaderSettings");
            InitLoaderVersion();
        }

        private void InitLoaderVersion()
        {
            DebugUtil.Log("Platform:", LoaderDefine.PlatformName);
            Loader.InitVersion(OnVersionInited);
        }

        private void OnVersionInited(AssetBundleManifest asset, bool suc)
        {
            if (!suc)
            {
                DebugUtil.LogWarning("Assetbundle Version Fail.");
                return;
            }

            DebugUtil.Log("Assetbundle Version Succ.");
            m_ButtonStart.SetActive(true);
            ServiceCenter.InitRegister();
            ResetServiceNodes();
        }

        public void OnClickStart()
        {
            m_ButtonStart.SetActive(false);
            StartInitService();
        }

        private void StartInitService()
        {
            ServiceCenter.Manager.StartInitalization(new Callback(OnServiceAllInited));
        }

        private void OnServiceAllInited(params object[] args)
        {
            Debug.LogWarning("OnServiceAllInited!");
            m_ButtonClear.SetActive(true);
        }

        public void OnClickClear()
        {
            m_ButtonClear.SetActive(false);
            ResetServiceNodes();
            m_ButtonStart.SetActive(true);
        }

        private void ResetServiceNodes()
        {
            m_Pool.UpdateToSize(0);
            var infos = ServiceManager.Config.ServiceInfos;
            m_Pool.UpdateToSize(infos.Length);
            for (var index = 0; index < m_Pool.Count; index++)
            {
                m_Pool[index].GetComponent<ServiceNode>().InitNode(infos[index]);
            }
        }
    }
}