#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;
using UnityEngine.Events;
#if UNITY_EDITOR
using UnityEditor;
#endif
using IGP.UnitySDK.Abstractions;
using IGP.UnitySDK.Models;
using IGP.UnitySDK.Core;
using IGP.UnitySDK.Network;
using IGP.UnitySDK.Protocol;

namespace IGP.UnitySDK
{
    public partial class IGPRuntimeManager
    {

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

            if (currentDesktopUserProfile != null && !currentDesktopUserProfile.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 EnsureDesktopSessionAsync(appId);
            EnsureDesktopUserContextAvailable();

            if (currentDesktopUserProfile != null && !currentDesktopUserProfile.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 EnsureDesktopSessionAsync(appIdOverride);
            EnsureDesktopUserContextAvailable();
            return await session.GetDesktopUserProfileAsync(RuntimeCancellationToken);
        }

        public async Task<IGPDesktopSessionCommandResult> GetDesktopPlayerProfilesAsync(
            string contentJson,
            int? appIdOverride = null)
        {
            var session = await EnsureDesktopSessionAsync(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 = currentDesktopUserProfile?.avatarVersion ?? string.Empty,
            };
        }

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

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

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

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