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

namespace AssetUpdate
{
    public class HttpsGetAction : IAssetAsyncAction
    {
        private DownloadJsonFile _action;
        private bool _done;
        
        public HttpsGetAction(float timeOut)
        {
            _action = GetVersionDownloader(timeOut);
            _action.onDownloadComplete = OnDownloadComplete;
        }

        public static DownloadJsonFile GetVersionDownloader(float timeOut)
        {
            var channelId = AssetUpdateManager.channel;
            var data = new Dictionary<string, string>
            {
                {"appid", channelId},
            };
            var action = new DownloadJsonFile(AssetUpdateManager.assetVersionUri, timeOut, data);
            return action;
        }
        
        public JsonData jsonData { get; private set; }

        public void Dispose()
        {
            if (_action != null)
            {
                _action.Dispose();
                _action = null;
            }
        }

        public bool UpdateTimeout()
        {
            return _done;
        }

        public void Start()
        {
            _action.Start();
        }

        private void OnDownloadComplete(DownloadJsonFile action)
        {
            _done = true;
            if (action == _action)
            {
                jsonData = action.jsonData;
                if (!string.IsNullOrEmpty(action.error))
                    Debug.LogError(action.error);
            }
        }
    }
}

internal interface IAssetAsyncAction
{
    bool UpdateTimeout();
    void Dispose();
}