using UnityEngine;
using _Core.Storage;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace _Core
{
    public class WebViewCache : MonoBehaviour
    {
        private string webViewCachePathDic = "webview-cache";
        private string currentCachePath;

        private static WebViewCache _instance;

        public static WebViewCache Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = FindObjectOfType<WebViewCache>();
                    if (_instance == null)
                    {
                        GameObject go = new GameObject("WebViewCache");
                        _instance = go.AddComponent<WebViewCache>();
                    }
                }
                return _instance;
            }
        }

        public string GetCurrentAvailableCachePath()
        {
            var dic = JsonConvert.DeserializeObject<Dictionary<string, bool>>(UserPrefs.GetString(webViewCachePathDic));
            
            foreach (KeyValuePair<string, bool> cache in dic)
            {
                if (!cache.Value)
                {
                    currentCachePath = cache.Key;
                    return cache.Key;
                }
            }
            currentCachePath = $"chromium-cache-{dic.Count + 1}";
            return currentCachePath;
        }

        public string GetWebViewCachePathDicKey()
        {
            return webViewCachePathDic;
        }

        private void Awake()
        {
            if (_instance == null)
            {
                _instance = this;
                DontDestroyOnLoad(gameObject); // 保证实例在场景切换时不被销毁
            }
            else if (_instance != this)
            {
                Destroy(gameObject); // 保证单例唯一性
            }
        }

        public void Start()
        {
            Application.quitting += OnQuit;
        }

        public void OnDestroy()
        {
            Application.quitting -= OnQuit;
        }


        private void OnQuit()
        {
            var dic = JsonConvert.DeserializeObject<Dictionary<string, bool>>(UserPrefs.GetString(webViewCachePathDic));
            dic[currentCachePath] = false;
            UserPrefs.SetString(webViewCachePathDic, JsonConvert.SerializeObject(dic));
        }
    }
}
