#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using IGP.UnitySDK.Abstractions;
using IGP.UnitySDK.Models;

namespace IGP.UnitySDK
{
    public partial class IGPRuntimeManager
    {
        // Bind both enable and disable to this exact session; never attach a new
        // session just to clean up an old subscription.
        internal Func<bool, Task<IGPDesktopSessionCommandResult>> CreateFriendsPresenceSubscriptionSender()
        {
            EnsureDesktopUserContextAvailable();
            var session = hostSessionClient;
            if (session == null || !session.IsAttached)
                throw new IGPSDKException("Host Session is not attached", IGPErrorCodes.ERR_HOST_SESSION_REQUIRED);
            var lifetime = RuntimeCancellationToken;
            return enabled => session.SendDesktopFriendCommandAsync(
                IGPDesktopSessionCommandType.SetStateSubscription,
                enabled ? "{\"topic\":\"friends.presence\",\"enabled\":true}"
                    : "{\"topic\":\"friends.presence\",\"enabled\":false}", lifetime);
        }

        internal async Task<IGPDesktopSessionCommandResult> SendDesktopFriendCommandAsync(
            IGPDesktopSessionCommandType command, string? contentJson, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, RuntimeCancellationToken);
            var session = await EnsureHostSessionAsync();
            EnsureDesktopUserContextAvailable();
            linked.Token.ThrowIfCancellationRequested();
            return await session.SendDesktopFriendCommandAsync(command, contentJson, linked.Token);
        }

        internal async Task<IGPDesktopSessionCommandResult> GetDesktopFriendsAsync()
        {
            var session = await EnsureHostSessionAsync();
            EnsureDesktopUserContextAvailable();
            return await session.GetDesktopFriendsAsync(RuntimeCancellationToken);
        }

        /// <summary>
        /// 获取当前 desktop 登录用户头像元信息。
        /// </summary>
        public async Task<IGPDesktopUserAvatarInfo> GetDesktopUserAvatarInfoAsync(int? appId = null)
        {
            var session = await EnsureHostSessionAsync(appId);
            EnsureDesktopUserContextAvailable();

            if (currentHostUserProfile != null && !currentHostUserProfile.avatarAvailable)
            {
                return BuildUnavailableDesktopUserAvatarInfo();
            }

            var info = await session.GetDesktopUserAvatarInfoAsync(RuntimeCancellationToken);
            UpdateCurrentDesktopUserAvatarInfo(info);
            return info;
        }

        /// <summary>
        /// 获取当前 desktop 登录用户头像 PNG 数据。
        /// </summary>
        public async Task<IGPDesktopUserAvatarImage> GetDesktopUserAvatarAsync(int? appId = null)
        {
            var session = await EnsureHostSessionAsync(appId);
            EnsureDesktopUserContextAvailable();

            if (currentHostUserProfile != null && !currentHostUserProfile.avatarAvailable)
            {
                return BuildUnavailableDesktopUserAvatarImage();
            }

            var image = await session.GetDesktopUserAvatarAsync(RuntimeCancellationToken);
            UpdateCurrentDesktopUserAvatarInfo(image.info);
            if (!image.info.available)
            {
                image.pngBytes = Array.Empty<byte>();
            }

            return image;
        }

        public async Task<IGPDesktopSessionCommandResult> GetDesktopUserProfileAsync(
            int? appIdOverride = null)
        {
            var session = await EnsureHostSessionAsync(appIdOverride);
            EnsureDesktopUserContextAvailable();
            return await session.GetDesktopUserProfileAsync(RuntimeCancellationToken);
        }

        public async Task<IGPDesktopSessionCommandResult> GetDesktopPlayerProfilesAsync(
            string contentJson,
            int? appIdOverride = null)
        {
            var session = await EnsureHostSessionAsync(appIdOverride);
            EnsureDesktopUserContextAvailable();
            return await session.GetDesktopPlayerProfilesAsync(
                contentJson ?? string.Empty,
                RuntimeCancellationToken);
        }

        private IGPDesktopUserAvatarInfo BuildUnavailableDesktopUserAvatarInfo()
        {
            return new IGPDesktopUserAvatarInfo
            {
                available = false,
                contentType = "image/png",
                width = 0,
                height = 0,
                encodedByteLength = 0,
                decodedByteLength = 0,
                avatarVersion = currentHostUserProfile?.avatarVersion ?? string.Empty,
            };
        }

        private IGPDesktopUserAvatarImage BuildUnavailableDesktopUserAvatarImage()
        {
            return new IGPDesktopUserAvatarImage
            {
                info = BuildUnavailableDesktopUserAvatarInfo(),
                pngBytes = Array.Empty<byte>(),
            };
        }

        private void UpdateCurrentDesktopUserAvatarInfo(IGPDesktopUserAvatarInfo? info)
        {
            if (info == null || currentHostUserProfile == null)
            {
                return;
            }

            currentHostUserProfile.avatarAvailable = info.available;
            if (!string.IsNullOrWhiteSpace(info.avatarVersion))
            {
                currentHostUserProfile.avatarVersion = info.avatarVersion;
            }
        }

        private void EnsureDesktopUserContextAvailable()
        {
            if (!(currentHostCapabilities?.userContext ?? false) ||
                currentHostUserContext == null ||
                string.IsNullOrWhiteSpace(currentHostUserContext.userId) ||
                !string.Equals(currentHostUserContext.loginState, "signedIn", StringComparison.OrdinalIgnoreCase))
            {
                throw new IGPSDKException(
                    "Desktop user context is required before desktop capabilities can be used",
                    IGPErrorCodes.ERR_HOST_USER_CONTEXT_REQUIRED);
            }
        }
    }
}
