using LightlessSync.API.Data;
using LightlessSync.API.Dto;
using LightlessSync.API.Dto.Chat;
using LightlessSync.API.Dto.Group;
using LightlessSync.API.Dto.User;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;
using System.Text;

namespace LightlessSync.WebAPI;

#pragma warning disable MA0040
public partial class ApiController
{
    public async Task PushCharacterData(CharacterData data, List<UserData> visibleCharacters)
    {
        if (!IsConnected) return;

        try
        {
            await PushCharacterDataInternal(data, [.. visibleCharacters]).ConfigureAwait(false);
        }
        catch (OperationCanceledException)
        {
            Logger.LogDebug("Upload operation was cancelled");
        }
        catch (Exception ex)
        {
            Logger.LogWarning(ex, "Error during upload of files");
        }
    }

    public async Task UserAddPair(UserDto user)
    {
        if (!IsConnected) return;
        await _lightlessHub!.SendAsync(nameof(UserAddPair), user).ConfigureAwait(false);
    }

    public async Task TryPairWithContentId(string otherCid)
    {
        if (!IsConnected) return;
        await _lightlessHub!.SendAsync(nameof(TryPairWithContentId), otherCid).ConfigureAwait(false);
    }

    public async Task UpdateChatPresence(ChatPresenceUpdateDto presence)
    {
        if (!IsConnected || _lightlessHub is null) return;
        await _lightlessHub.InvokeAsync(nameof(UpdateChatPresence), presence).ConfigureAwait(false);
    }

    public async Task SendChatMessage(ChatSendRequestDto request)
    {
        if (!IsConnected || _lightlessHub is null) return;
        await _lightlessHub.InvokeAsync(nameof(SendChatMessage), request).ConfigureAwait(false);
    }

    public async Task ReportChatMessage(ChatReportSubmitDto request)
    {
        if (!IsConnected || _lightlessHub is null) return;
        await _lightlessHub.InvokeAsync(nameof(ReportChatMessage), request).ConfigureAwait(false);
    }

    public async Task SetChatParticipantMute(ChatParticipantMuteRequestDto request)
    {
        if (!IsConnected || _lightlessHub is null) return;
        await _lightlessHub.InvokeAsync(nameof(SetChatParticipantMute), request).ConfigureAwait(false);
    }
    public async Task SetBroadcastStatus(bool enabled, GroupBroadcastRequestDto? groupDto = null)
    {
        CheckConnection();
        await _lightlessHub!.InvokeAsync(nameof(SetBroadcastStatus), enabled, groupDto).ConfigureAwait(false);
    }

    public async Task<BroadcastStatusInfoDto?> IsUserBroadcasting(string hashedCid)
    {
        CheckConnection();
        return await _lightlessHub!.InvokeAsync<BroadcastStatusInfoDto?>(nameof(IsUserBroadcasting), hashedCid).ConfigureAwait(false);
    }

    public async Task<BroadcastStatusBatchDto> AreUsersBroadcasting(List<string> hashedCids)
    {
        CheckConnection();
        return await _lightlessHub!.InvokeAsync<BroadcastStatusBatchDto>(nameof(AreUsersBroadcasting), hashedCids).ConfigureAwait(false);
    }

    public async Task<TimeSpan?> GetBroadcastTtl()
    {
        CheckConnection();
        return await _lightlessHub!.InvokeAsync<TimeSpan?>(nameof(GetBroadcastTtl)).ConfigureAwait(false);
    }

    public async Task UserDelete()
    {
        CheckConnection();
        await _lightlessHub!.SendAsync(nameof(UserDelete)).ConfigureAwait(false);
        await CreateConnectionsAsync().ConfigureAwait(false);
    }

    public async Task<List<OnlineUserIdentDto>> UserGetOnlinePairs(CensusDataDto? censusDataDto)
    {
        return await _lightlessHub!.InvokeAsync<List<OnlineUserIdentDto>>(nameof(UserGetOnlinePairs), censusDataDto).ConfigureAwait(false);
    }

    public async Task<List<UserFullPairDto>> UserGetPairedClients()
    {
        return await _lightlessHub!.InvokeAsync<List<UserFullPairDto>>(nameof(UserGetPairedClients)).ConfigureAwait(false);
    }

    public async Task<UserProfileDto> UserGetProfile(UserDto dto)
    {
        if (!IsConnected) return new UserProfileDto(dto.User, Disabled: false, IsNSFW: null, ProfilePictureBase64: null, Description: null, BannerPictureBase64: null, Tags: null);
        return await _lightlessHub!.InvokeAsync<UserProfileDto>(nameof(UserGetProfile), dto).ConfigureAwait(false);
    }

    public async Task<UserProfileDto?> UserGetLightfinderProfile(string hashedCid)
    {
        if (!IsConnected) return null;
        return await _lightlessHub!.InvokeAsync<UserProfileDto?>(nameof(UserGetLightfinderProfile), hashedCid).ConfigureAwait(false);
    }

    public async Task UserPushData(UserCharaDataMessageDto dto)
    {
        try
        {
            await _lightlessHub!.InvokeAsync(nameof(UserPushData), dto).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            Logger.LogWarning(ex, "Failed to Push character data");
        }
    }

    public async Task SetBulkPermissions(BulkPermissionsDto dto)
    {
        CheckConnection();

        try
        {
            await _lightlessHub!.InvokeAsync(nameof(SetBulkPermissions), dto).ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            Logger.LogWarning(ex, "Failed to set permissions");
        }
    }

    public async Task UserRemovePair(UserDto userDto)
    {
        if (!IsConnected) return;
        await _lightlessHub!.SendAsync(nameof(UserRemovePair), userDto).ConfigureAwait(false);
    }

    public async Task UserSetPairPermissions(UserPermissionsDto userPermissions)
    {
        await SetBulkPermissions(new(new(StringComparer.Ordinal)
        {
                { userPermissions.User.UID, userPermissions.Permissions }
            }, new(StringComparer.Ordinal))).ConfigureAwait(false);
    }

    public async Task UserSetProfile(UserProfileDto userDescription)
    {
        if (!IsConnected) return;
        await _lightlessHub!.InvokeAsync(nameof(UserSetProfile), userDescription).ConfigureAwait(false);
    }

    public async Task UserUpdateVanityColors(UserVanityColorsDto dto)
    {
        if (!IsConnected) return;
        await _lightlessHub!.InvokeAsync(nameof(UserUpdateVanityColors), dto).ConfigureAwait(false);
    }

    public async Task UserUpdateDefaultPermissions(DefaultPermissionsDto defaultPermissionsDto)
    {
        CheckConnection();
        await _lightlessHub!.InvokeAsync(nameof(UserUpdateDefaultPermissions), defaultPermissionsDto).ConfigureAwait(false);
    }

    private async Task PushCharacterDataInternal(CharacterData character, List<UserData> visibleCharacters)
    {
        Logger.LogInformation("Pushing character data for {hash} to {charas}", character.DataHash.Value, string.Join(", ", visibleCharacters.Select(c => c.AliasOrUID)));
        StringBuilder sb = new();
        foreach (var kvp in character.FileReplacements.ToList())
        {
            sb.AppendLine($"FileReplacements for {kvp.Key}: {kvp.Value.Count}");
        }
        foreach (var item in character.GlamourerData)
        {
            sb.AppendLine($"GlamourerData for {item.Key}: {!string.IsNullOrEmpty(item.Value)}");
        }
        Logger.LogDebug("Chara data contained: {nl} {data}", Environment.NewLine, sb.ToString());

        CensusDataDto? censusDto = null;
        if (_serverManager.SendCensusData && _lastCensus != null)
        {
            var world = _dalamudUtil.GetWorldId();
            censusDto = new((ushort)world, _lastCensus.RaceId, _lastCensus.TribeId, _lastCensus.Gender);
            Logger.LogDebug("Attaching Census Data: {data}", censusDto);
        }

        await UserPushData(new(visibleCharacters, character, censusDto)).ConfigureAwait(false);
    }
    
    public async Task UpdateLocation(LocationDto locationDto, bool offline = false)
    {
        if (!IsConnected) return;
        await _lightlessHub!.SendAsync(nameof(UpdateLocation), locationDto, offline).ConfigureAwait(false);
    }
    public async Task<(List<LocationWithTimeDto>, List<SharingStatusDto>)> RequestAllLocationInfo()
    {
        if (!IsConnected) return ([],[]);
        return await _lightlessHub!.InvokeAsync<(List<LocationWithTimeDto>, List<SharingStatusDto>)>(nameof(RequestAllLocationInfo)).ConfigureAwait(false);
    }
    public async Task<bool> ToggleLocationSharing(LocationSharingToggleDto dto)
    {
        if (!IsConnected) return false;
        return await _lightlessHub!.InvokeAsync<bool>(nameof(ToggleLocationSharing), dto).ConfigureAwait(false);
    }
}
#pragma warning restore MA0040