﻿using JLGames.RocketDriver.Samples.RpgMaterialDemo.Service.Material;
using JLGames.RocketDriver.Actions.Loaderx;
using JLGames.RocketDriver.Actions.Utils;
using JLGames.RocketDriver.CSharp;
using JLGames.RocketDriver.CSharp.DateTimex;
using JLGames.RocketDriver.Games.NetManager;
using JLGames.RocketDriver.Games.RpgMaterial.Material;
using JLGames.RocketDriver.Samples.RpgMaterialDemo.Server;
using JLGames.RocketDriver.Samples.RpgMaterialDemo.Service;
using UnityEngine;

namespace JLGames.RocketDriver.Samples.RpgMaterialDemo.Scripts
{
    public class RpgMaterialDemo : MonoBehaviour
    {
        [SerializeField] private GameObject m_GmPanel;

        private void Start()
        {
            InitVirtulNet();
            InitLoader();
        }

        private void InitVirtulNet()
        {
            var server = new LogicalServer();
            NetManager.Shared.Register(server, true);
            server.Startup();
            var client = new LogicalClient();
            NetManager.Shared.Register(client, true);
            client.Connect(server);
        }

        private void InitLoader()
        {
            Loader.InitLoader("RpgMaterialLoaderSettings");
            Loader.InitVersion(OnVersionInited);
        }

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

            DebugUtil.Log("Assetbundle Version Succ.");
            ServiceCenter.InitRegister();
            ServiceCenter.Manager.StartInitalization(new Callback(OnServiceAllInited));
        }

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

        private void TraceItemValid()
        {
            var itemService = ServiceCenter.MaterialItemService;
            var items = itemService.GetMaterials();
            var nowTicks = DateTimeUtil.NowTicks;
            foreach (var item in items)
            {
                DebugUtil.LogWarning("----------");
                DebugUtil.Log($"{item.Id} Valid[Enabled={item.ValidEnabled}, Type={item.ValidType}, Check={item.CheckValid(nowTicks)}]");
                if (item.ValidType == MaterialValidType.None) continue;
                if (item.ValidType == MaterialValidType.Stamp)
                {
                    DebugUtil.Log($"CheckStamp={item.CheckValid(nowTicks)}");
                }
                else
                {
                    DebugUtil.Log($"CheckDuration={item.CheckValid(nowTicks)}");
                }
            }
        }
    }
}