using UnityEngine;
using XGame.Framework.Asset;
using XGame.Framework.Asyncs;
using XGame.Framework.Serialization;

namespace XGame.Framework.Database
{
    public class DatabaseAsync<TTable> : Async, IDatabaseAsync<TTable> where TTable : class, ITable
    {
        public string TableName { get; private set; }
        //private string _text;

        private IAssetLoadAsync<TextAsset> _loadAsync;

        private byte[] _bytes;

        public DatabaseAsync(string tableName)
        {
            TableName = tableName;
        }
        public TRepository GetResult<TRepository>() where TRepository : TableRepository<TTable, TRepository>
        {
            if (_bytes == null || _bytes.Length == 0)
            {
                return default;
            }
            return SerializationUtils.Read<TRepository>(_bytes);
            //if (string.IsNullOrEmpty(_text))
            //{
            //    return default(T[]);
            //}
            //return XJson.ToObject<T[]>(_text);
        }
        protected override void OnRemoveAll()
        {
            _loadAsync?.RemoveOn(OnLoaded);
            _loadAsync = null;
            _bytes = null;
        }

        public void Start()
        {
            _loadAsync = AssetManager.LoadAsync<TextAsset>(TableName);
            _loadAsync.On(OnLoaded);
            //try
            //{
            //    var uri = FileUtils.GetFileUrl($"Tables/{TableName}.json");
            //    var request = UnityWebRequest.Get(uri);
            //    var operation = request.SendWebRequest();
            //    operation.completed += (op) =>
            //    {
            //        if (request.result == UnityWebRequest.Result.Success)
            //        {
            //            _text = request.downloadHandler.text;
            //        }
            //        else
            //        {
            //            _text = string.Empty;
            //            State = request.error;
            //            Log.Error($"DatabaseAsync failed. URL:{uri} Result:{request.result} Error:{request.error}");
            //        }
            //        Completed();
            //    };
            //}
            //catch (Exception ex)
            //{
            //    Log.Exception($"DatabaseAsync Name:{TableName}", ex);
            //}

        }
        private void OnLoaded(IAsync _)
        {
            var loadAsync = _loadAsync;
            _loadAsync = null;
            var result = loadAsync.Result;
            _bytes = result?.bytes ?? null;
            State = loadAsync.State;
            Completed();
            AssetManager.Recycle(result);
        }
    }
}

