// Copyright (c) 2026 EzAdmin. All rights reserved.
// Licensed under the EzAdmin Client License. See LICENSE-CLIENT.txt.

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

namespace EzAdmin.Client
{

    public static class EzAdminItems
    {
        private static readonly Dictionary<string, EzAdminClient.OwnedItem> ById =
            new Dictionary<string, EzAdminClient.OwnedItem>(StringComparer.OrdinalIgnoreCase);
        private static readonly Dictionary<string, EzAdminClient.OwnedItem> ByName =
            new Dictionary<string, EzAdminClient.OwnedItem>(StringComparer.OrdinalIgnoreCase);
        private static bool _started;
        private static bool _loading;

        public static bool Loaded { get; private set; }

        public static event Action Changed;

        public static IEnumerable<EzAdminClient.OwnedItem> All => ById.Values;

        public static bool Has(string idOrName)
        {
            if (string.IsNullOrEmpty(idOrName)) return false;
            return ById.ContainsKey(idOrName) || ByName.ContainsKey(idOrName);
        }

        public static int Count(string idOrName)
        {
            EzAdminClient.OwnedItem item;
            if (ById.TryGetValue(idOrName ?? "", out item) || ByName.TryGetValue(idOrName ?? "", out item))
            {
                return Math.Max(1, item.amount);
            }
            return 0;
        }

        public static void Start()
        {
            if (_started) return;
            var client = EzAdminClient.Instance;
            if (client == null) return;
            _started = true;
            EzAdminClient.ItemsChanged += Refresh;
            EzAdminLink.Linked += _ => Refresh();
            client.StartCoroutine(FirstLoad());
        }

        public static void Refresh()
        {
            var client = EzAdminClient.Instance;
            if (client == null || _loading) return;
            _loading = true;
            client.GetOwnedItems(items =>
            {
                _loading = false;
                if (items == null) return;
                ById.Clear();
                ByName.Clear();
                foreach (var item in items)
                {
                    if (string.IsNullOrEmpty(item.id)) continue;
                    ById[item.id] = item;
                    if (!string.IsNullOrEmpty(item.name)) ByName[item.name] = item;
                }
                Loaded = true;
                Changed?.Invoke();
            });
        }

        private static IEnumerator FirstLoad()
        {
            while (EzAdminClient.Instance != null && !EzAdminClient.Instance.IsConnected)
            {
                yield return new WaitForSecondsRealtime(1f);
            }
            Refresh();
        }

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
        private static void ResetOnPlay()
        {
            ById.Clear();
            ByName.Clear();
            _started = false;
            _loading = false;
            Loaded = false;
            Changed = null;
        }
    }
}
