using System;
using System.Runtime.CompilerServices;
using UnityEngine.Networking;

namespace MajacloudSdk.Internal
{
    /// <summary>
    /// `await request.SendWebRequest()`. The completion callback fires on the
    /// main thread, so continuations never need a SynchronizationContext —
    /// this is what keeps the SDK working on WebGL.
    /// </summary>
    internal struct UnityWebRequestAwaiter : INotifyCompletion
    {
        private readonly UnityWebRequestAsyncOperation _operation;

        public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation operation)
        {
            _operation = operation;
        }

        public bool IsCompleted => _operation == null || _operation.isDone;

        public void OnCompleted(Action continuation)
        {
            if (_operation == null || _operation.isDone)
            {
                continuation();
                return;
            }
            _operation.completed += _ => continuation();
        }

        public UnityWebRequest GetResult() => _operation?.webRequest;
    }

    internal static class UnityWebRequestExtensions
    {
        public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation operation) => new UnityWebRequestAwaiter(operation);
    }
}
