using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace PlayPcSdkManaged.Unity.Recall
{
    public class GameRecallClient : IDisposable
    {
        private IntPtr _client;

        private readonly IGamesRecallCallbacksHandler _callbackHander;


        public GameRecallClient(IGamesRecallCallbacksHandler callbacksHandler)
        {
            _callbackHander = callbacksHandler ?? throw new ArgumentNullException("callbacksHandler");
            _client = GameRecallInterop._GamesRecallClient_Create();
            if (_client == IntPtr.Zero)
            {
                throw new InvalidOperationException("Failed to create native gamerecallclient instance.");
            }

        }
        ~GameRecallClient()
        {
            Dispose(disposing: false);
        }

        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            IntPtr intPtr = Interlocked.Exchange(ref _client, IntPtr.Zero);
            if (intPtr != IntPtr.Zero)
            {
                GameRecallInterop._GamesRecallClient_Destroy(intPtr);
            }
        }


        public Task<RequestRecallAccessResult> RequestRecallAccessAsync()
        {
            TaskCompletionSource<RequestRecallAccessResult> taskCompletionSource = new TaskCompletionSource<RequestRecallAccessResult>();
            RequestRecallAccess(taskCompletionSource.SetResult);
            return taskCompletionSource.Task;
        }

        public void RequestRecallAccess(RequestRecallAccessContinuation continuation)
        {
            GCHandle value = GCHandle.Alloc(continuation);
            GameRecallInterop._GamesRecallClient_RequestRecallAccess(_client, GCHandle.ToIntPtr(value), _callbackHander.RequestRecallAccessCallback);
        }
    }
}
