#nullable enable
using System;
using System.Threading.Tasks;
using UnityEngine;

namespace IGP.UnitySDK
{
    public partial class IGPRuntimeManager
    {
        private interface IIGPHostSessionPlatformRuntime : IDisposable
        {
            IGPHostSessionPlatform Platform { get; }
            string TransportName { get; }
            string ConnectionSource { get; }
            string AttachedReason { get; }
            string DetachedReason { get; }
            string LogEndpoint { get; }
            IIGPMultiplayerBootstrapProvider? MultiplayerBootstrapProvider { get; }

            IIGPHostSessionTransport CreateTransport();
            IGPDesktopSessionAttachRequest CreateAttachRequest(int appId);
            Task InitializeSessionAsync();
            Task<bool> RecoverUnavailableSessionAsync(int? appIdOverride);
            Task<bool> AuthorizeAsync();
            void Tick();
            void OnAttachSucceeded();
            void ScheduleAttachRecoveryIfNeeded();
            void ScheduleAuthorizationRecoveryIfNeeded();
        }

        private abstract class IGPHostSessionPlatformRuntimeBase : IIGPHostSessionPlatformRuntime
        {
            protected readonly IGPRuntimeManager Runtime;

            protected IGPHostSessionPlatformRuntimeBase(IGPRuntimeManager runtime)
            {
                Runtime = runtime ?? throw new ArgumentNullException(nameof(runtime));
            }

            public abstract IGPHostSessionPlatform Platform { get; }
            public abstract string TransportName { get; }
            public abstract string ConnectionSource { get; }
            public abstract string AttachedReason { get; }
            public abstract string DetachedReason { get; }
            public abstract string LogEndpoint { get; }
            public virtual IIGPMultiplayerBootstrapProvider? MultiplayerBootstrapProvider => null;

            protected bool ShouldAutoAttach =>
                Runtime.initializeRequested &&
                (Runtime.config == null || Runtime.config.desktopSessionAutoAttach);

            public abstract IIGPHostSessionTransport CreateTransport();
            public abstract IGPDesktopSessionAttachRequest CreateAttachRequest(int appId);
            public abstract Task InitializeSessionAsync();
            public abstract Task<bool> RecoverUnavailableSessionAsync(int? appIdOverride);
            public abstract Task<bool> AuthorizeAsync();
            public abstract void Tick();
            public abstract void OnAttachSucceeded();
            public abstract void ScheduleAttachRecoveryIfNeeded();
            public abstract void ScheduleAuthorizationRecoveryIfNeeded();
            public abstract void Dispose();

            protected IGPDesktopSessionAttachRequest CreateCommonAttachRequest(
                int appId,
                string executablePath,
                int processId)
            {
                return new IGPDesktopSessionAttachRequest
                {
                    AppId = appId,
                    ExecutablePath = executablePath,
                    ProcessId = processId,
                    SdkVersion = Runtime.ResolveSdkVersion(),
                    EngineVersion = Application.unityVersion,
                };
            }
        }

        internal static T ResolveAndCreateHostSessionRuntime<T>(
            Func<IGPHostSessionPlatform, bool> isSupported,
            Func<IGPHostSessionPlatform, T> createRuntime)
        {
            if (isSupported == null) throw new ArgumentNullException(nameof(isSupported));
            if (createRuntime == null) throw new ArgumentNullException(nameof(createRuntime));

            var priority = new[]
            {
                IGPHostSessionPlatform.Desktop,
                IGPHostSessionPlatform.Mobile,
            };
            foreach (var platform in priority)
            {
                if (isSupported(platform))
                {
                    return createRuntime(platform);
                }
            }

            throw new IGPSDKException(
                $"Host Session is not supported on Unity runtime platform {Application.platform}",
                Models.IGPErrorCodes.ERR_HOST_SESSION_REQUIRED);
        }

        private async Task InitializeHostSessionPlatformAsync()
        {
            hostSessionPlatformRuntime = ResolveAndCreateHostSessionRuntime(
                IsHostSessionPlatformSupported,
                CreateHostSessionPlatformRuntime);
            LogSessionStart();
            await HostSessionPlatformRuntime.InitializeSessionAsync();
        }

        private IIGPHostSessionPlatformRuntime CreateHostSessionPlatformRuntime(
            IGPHostSessionPlatform platform)
        {
            return platform == IGPHostSessionPlatform.Mobile
                ? new IGPMobileHostSessionPlatformRuntime(this)
                : new IGPDesktopHostSessionPlatformRuntime(this);
        }

        private static bool IsHostSessionPlatformSupported(IGPHostSessionPlatform platform)
        {
            switch (platform)
            {
                case IGPHostSessionPlatform.Desktop:
                    return Application.platform == RuntimePlatform.WindowsEditor ||
                        Application.platform == RuntimePlatform.WindowsPlayer;
                case IGPHostSessionPlatform.Mobile:
                    return Application.platform == RuntimePlatform.Android ||
                        Application.platform == RuntimePlatform.IPhonePlayer;
                default:
                    return false;
            }
        }
    }
}
