﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.Chat;
using Photon.Muninn;
using Unity.Muninn;
using Unity.Muninn.Model;
using Unity.Muninn.MuninnLobby;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using MuninnRaiseEventOptions = Unity.Muninn.Model.RaiseEventOptions;


internal partial class MuninnPeer : LoadBalancingPeer
{
    public MuninnPeer(IPhotonPeerListener listener, ConnectionProtocol protocolType) : base(listener,
        protocolType)
    {
    }

    protected MuninnPeer(ConnectionProtocol protocolType) : base(protocolType)
    {
    }

    private MuninnPeerBehaviour _muninnPeerBehaviour;

    private NetworkingPeer Client => Listener as NetworkingPeer;

    public new int ServerTimeInMilliSeconds
    {
        get
        {
            if (!_muninnPeerBehaviour || !_muninnPeerBehaviour.ServerTimeDelta.HasValue)
            {
                return 0;
            }

            return (int)(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() +
                         _muninnPeerBehaviour.ServerTimeDelta.Value);
        }
    }

    protected new bool EstablishEncryption()
    {
        _muninnPeerBehaviour.EnqueueIncomingCommand(OnEncryptionEstablished);
        return true;
    }

    public new PeerStateValue PeerState { get; private set; }

    public override bool SendOutgoingCommands()
    {
        return _muninnPeerBehaviour && _muninnPeerBehaviour.SendOutgoingCommands();
    }

    public override bool DispatchIncomingCommands()
    {
        return _muninnPeerBehaviour && _muninnPeerBehaviour.DispatchIncomingCommands();
    }

    public override bool Connect(string serverAddress, string applicationName)
    {
        return Connect(serverAddress, applicationName, null);
    }

    public override bool Connect(string serverAddress, string applicationName, object custom)
    {
        SetupBehaviour();
        PeerState = PeerStateValue.Connecting;
        _muninnPeerBehaviour.EnqueueIncomingCommand(OnConnected);
        return true;
    }

    public override bool OpJoinLobby(TypedLobby lobby = null)
    {
        _muninnPeerBehaviour.StartCoroutine(RespondJoinLobby());
        return true;
    }

    public override bool OpLeaveLobby()
    {
        _muninnPeerBehaviour.EnqueueIncomingCommand(() =>
        {
            if (!PhotonNetwork.insideLobby)
                return;

            Listener.OnOperationResponse(new OperationResponse
            {
                OperationCode = OperationCode.LeaveLobby,
                Parameters = new Dictionary<byte, object>()
            });
        });
        return true;
    }

    public override bool OpJoinRandomRoom(OpJoinRandomRoomParams opJoinRandomRoomParams)
    {
        _lastJoinOperationCode = OperationCode.JoinRandomGame;
        _muninnPeerBehaviour.StartCoroutine(GetRandomRoom());
        return true;

        IEnumerator GetRandomRoom()
        {
            ListRoomResponse lobbyResponse = null;
            yield return MuninnLobbyService.AsyncListRoom(new ListRoomRequest
            {
                Count = int.MaxValue
            }, response => lobbyResponse = response);
            // 处理异常流
            if (lobbyResponse.Code != (uint)MuninnCode.OK)
            {
                Listener.OnOperationResponse(new OperationResponse
                {
                    OperationCode = OperationCode.JoinRandomGame,
                    Parameters = new Dictionary<byte, object>(),
                    ReturnCode = ErrorCode.InvalidAuthentication,
                    DebugMessage = ErrorMessages.AuthTokenInvalid
                });
                yield break;
            }

            OnQueryRandomRoom(lobbyResponse, opJoinRandomRoomParams);
        }
    }

    public override bool OpJoinRoom(EnterRoomParams opParams)
    {
        if (!opParams.OnGameServer)
        {
            RespondOpJoinRoomByQuery(opParams);
        }
        // 真实的加入请求
        else
        {
            var properties = opParams.PlayerProperties;
            if (properties != null)
            {
                if (properties.TryGetValue(ActorProperties.PlayerName, out var property))
                {
                    MuninnNetwork.PlayerInfo.Name = (string)property;
                }

                MuninnNetwork.PlayerInfo.Properties = properties.StripToStringKeys().ToDictionary();
            }

            _lastJoinOperationCode = OperationCode.JoinGame;
            MuninnNetwork.JoinRoom(new JoinRoomRequest
            {
                RoomUuid = opParams.RoomName
            });
        }

        return true;
    }

    public override bool OpCreateRoom(EnterRoomParams opParams)
    {
        // 模拟返回 Game server 的地址
        if (!opParams.OnGameServer)
        {
            var response = new OperationResponse
            {
                OperationCode = OperationCode.CreateGame,
                Parameters = new Dictionary<byte, object>
                {
                    [ParameterCode.Address] = UosIP
                }
            };
            _muninnPeerBehaviour.EnqueueIncomingCommand(() => { Listener.OnOperationResponse(response); });
        }
        // 真实的创建请求
        else
        {
            var properties = opParams.PlayerProperties;
            if (properties != null)
            {
                if (properties.TryGetValue(ActorProperties.PlayerName, out var property))
                {
                    MuninnNetwork.PlayerInfo.Name = (string)property;
                }

                MuninnNetwork.PlayerInfo.Properties = properties.StripToStringKeys().ToDictionary();
            }

            // 若房间名为空，设置默认的房间名称
            if (string.IsNullOrEmpty(opParams.RoomName))
            {
                opParams.RoomName = $"Room {Guid.NewGuid().ToString().Substring(0, 4)}";
            }

            var request = new CreateRoomRequest
            {
                Name = opParams.RoomName,
                PlayerId = MuninnNetwork.PlayerInfo.Id,
            };

            if (opParams.RoomOptions != null)
            {
                request.MaxPlayers = opParams.RoomOptions.MaxPlayers;
                request.Visibility = opParams.RoomOptions.IsVisible
                    ? MuninnRoomVisibility.Public
                    : MuninnRoomVisibility.Private;
                request.CustomProperties = opParams.RoomOptions.CustomRoomProperties.ToDictionary();
            }

            _lastJoinOperationCode = OperationCode.CreateGame;
            MuninnNetwork.CreateAndJoinRoom(request);
        }

        return true;
    }

    public override bool OpLeaveRoom(bool becomeInactive)
    {
        MuninnNetwork.LeaveRoom();
        return true;
    }

    public override bool OpChangeGroups(byte[] groupsToRemove, byte[] groupsToAdd)
    {
        MuninnNetwork.UnsubscribeGroups(groupsToRemove?.Select(num => (uint)num).ToList());
        MuninnNetwork.SubscribeGroups(groupsToAdd?.Select(num => (uint)num).ToList());
        return true;
    }

    public override bool OpAuthenticate(string appId, string appVersion, AuthenticationValues authValues,
        string regionCode,
        bool getLobbyStatistics)
    {
        var response = new OperationResponse
        {
            OperationCode = OperationCode.Authenticate,
            Parameters = new Dictionary<byte, object>
            {
                [ParameterCode.UserId] = MuninnNetwork.PlayerInfo.Id
            }
        };
        MuninnNetwork.ListRooms(new ListRoomRequest
        {
            Count = 0
        }, lobbyResponse =>
        {
            if (lobbyResponse.Code != (uint)MuninnCode.OK)
            {
                response.ReturnCode = ErrorCode.InvalidAuthentication;
                response.DebugMessage = ErrorMessages.AuthTokenInvalid;
            }

            Listener.OnOperationResponse(response);
        });
        return true;
    }

    public override bool OpAuthenticateOnce(string appId, string appVersion, AuthenticationValues authValues,
        string regionCode,
        EncryptionMode encryptionMode, ConnectionProtocol expectedProtocol)
    {
        var response = new OperationResponse
        {
            OperationCode = OperationCode.AuthenticateOnce,
            Parameters = new Dictionary<byte, object>
            {
                [ParameterCode.UserId] = MuninnNetwork.PlayerInfo.Id
            }
        };
        MuninnNetwork.ListRooms(new ListRoomRequest
        {
            Count = 0
        }, lobbyResponse =>
        {
            if (lobbyResponse.Code != (uint)MuninnCode.OK)
            {
                response.ReturnCode = ErrorCode.InvalidAuthentication;
                response.DebugMessage = ErrorMessages.AuthTokenInvalid;
            }

            Listener.OnOperationResponse(response);
        });
        return true;
    }

    public override bool OpGetRegions(string appId)
    {
        var response = new OperationResponse
        {
            OperationCode = OperationCode.GetRegions,
            Parameters = new Dictionary<byte, object>()
        };
        MuninnNetwork.ListRooms(new ListRoomRequest
        {
            Count = 0
        }, lobbyResponse =>
        {
            if (lobbyResponse.Code != (uint)MuninnCode.OK)
            {
                response.ReturnCode = ErrorCode.InvalidAuthentication;
                response.DebugMessage = ErrorMessages.AuthTokenInvalid;
            }
            else
            {
                var enabledRegions = PhotonNetwork.PhotonServerSettings.EnabledRegions;
                var region = PhotonNetwork.PhotonServerSettings.PreferredRegion;
                if (region == CloudRegionCode.none ||
                    (enabledRegions & Region.ParseFlag(region)) == 0)
                {
                    region = Enum.GetValues(typeof(CloudRegionCode)).Cast<CloudRegionCode>()
                        .FirstOrDefault(code => (enabledRegions & Region.ParseFlag(code)) != 0);
                }

                var regions = new[] { Enum.GetName(typeof(CloudRegionCode), region) };
                var servers = new[] { UosIP };
                response.Parameters[ParameterCode.Region] = regions;
                response.Parameters[ParameterCode.Address] = servers;
            }

            Listener.OnOperationResponse(response);
        });
        return true;
    }

    public override void FetchServerTimestamp()
    {
        _muninnPeerBehaviour.FetchTimestamp();
    }

    public override void Disconnect()
    {
        if (PeerState != PeerStateValue.Disconnected)
        {
            PeerState = PeerStateValue.Disconnecting;
        }

        if (_muninnPeerBehaviour.IsConnected)
        {
            MuninnNetwork.Disconnect();
        }
        else
        {
            _muninnPeerBehaviour.EnqueueIncomingCommand(OnDisconnected);
        }
    }


    protected internal override bool OpSetPropertiesOfActor(int actorNr, Hashtable actorProperties,
        Hashtable expectedProperties = null,
        bool webForward = false)
    {
        var needBack = expectedProperties != null && expectedProperties.Any();

        var player = Client.GetPlayerWithId(actorNr);

        var muninnPlayer = new MuninnPlayer
        {
            Id = player.UserId,
            Name = player.NickName,
            SenderId = (uint)player.ID,
        };

        if (actorProperties.TryGetValue(ActorProperties.PlayerName, out var name))
        {
            muninnPlayer.Name = (string)name;
        }

        muninnPlayer.Properties = player.CustomProperties.ToPrettyDictionary(actorProperties);

        MuninnNetwork.UpdatePlayerInfo(muninnPlayer, response => OnUpdatePlayerInfo(response, needBack));
        return true;
    }

    protected internal override bool OpSetPropertiesOfRoom(Hashtable gameProperties,
        Hashtable expectedProperties = null, bool webForward = false)
    {
        var needBack = expectedProperties != null && expectedProperties.Any();
        var room = Client.CurrentRoom;
        if (gameProperties.TryGetValue(GamePropertyKey.IsOpen, out var isOpen))
        {
            var uuid = _muninnPeerBehaviour.GetMuninnRoom().Id;
            var statusToChange = (bool)isOpen ? StatusToChange.Ready : StatusToChange.Running;
            MuninnNetwork.ChangeRoomStatus(uuid, statusToChange, null);
        }

        var newProperties = room.CustomProperties.ToPrettyDictionary(gameProperties);
        MuninnNetwork.UpdateRoomCustomProperties(newProperties,
            response => OnUpdateRoomCustomProperties(response, needBack));
        return true;
    }

    public override bool OpRaiseEvent(byte eventCode, object customEventContent, bool sendReliable,
        RaiseEventOptions raiseEventOptions)
    {
        var contentBytes = SerializationUtil.Serialize(customEventContent);
        var receiverIds = raiseEventOptions?.TargetActors?.Select(i => (uint)i).ToArray();

        #region Cache operation

        var slice = (customEventContent as Hashtable)?[ParameterCode.CacheSliceIndex] as int? ?? 0;
        switch (raiseEventOptions?.CachingOption)
        {
            case EventCaching.SliceIncreaseIndex:
                MuninnNetwork.OperateSlice(SliceOperation.SliceIncreaseIndex, slice);
                return true;
            case EventCaching.SliceSetIndex:
                MuninnNetwork.OperateSlice(SliceOperation.SliceSetIndex, slice);
                return true;
            case EventCaching.SlicePurgeIndex:
                MuninnNetwork.OperateSlice(SliceOperation.SlicePurgeIndex, slice);
                return true;
            case EventCaching.SlicePurgeUpToIndex:
                MuninnNetwork.OperateSlice(SliceOperation.SlicePurgeUpToIndex, slice);
                return true;
            case EventCaching.RemoveFromRoomCache:
                MuninnNetwork.RemoveCodedCache(eventCode, contentBytes, receiverIds);
                Listener.OnOperationResponse(new OperationResponse
                {
                    OperationCode = OperationCode.RaiseEvent,
                    Parameters = new Dictionary<byte, object>()
                });
                return true;
            case EventCaching.RemoveFromRoomCacheForActorsLeft:
                MuninnNetwork.ClearInvalidCodedCache();
                Listener.OnOperationResponse(new OperationResponse
                {
                    OperationCode = OperationCode.RaiseEvent,
                    Parameters = new Dictionary<byte, object>()
                });
                return true;
        }

        #endregion

        #region Construct event

        var eventData = new Hashtable
        {
            [ParameterCode.Code] = eventCode
        };
        if (customEventContent != null)
        {
            eventData[ParameterCode.Data] = customEventContent;
        }

        var data = SerializationUtil.Serialize(eventData);

        #endregion

        #region Set targets

        var muninnRaiseEventOptions = new MuninnRaiseEventOptions
        {
            Target = RaiseEventTarget.TO_ALL_BUT_ME
        };

        if (raiseEventOptions != null)
        {
            if (raiseEventOptions.TargetActors != null)
            {
                muninnRaiseEventOptions.ReceiverIds = receiverIds;
                muninnRaiseEventOptions.Target = RaiseEventTarget.TO_PLAYERS;
            }
            else if (raiseEventOptions.InterestGroup != 0)
            {
                muninnRaiseEventOptions.TargetGroups = new uint[] { raiseEventOptions.InterestGroup };
                muninnRaiseEventOptions.Target = RaiseEventTarget.TO_GROUPS;
            }
            else if (raiseEventOptions.Receivers == ReceiverGroup.All)
            {
                muninnRaiseEventOptions.Target = RaiseEventTarget.TO_ALL;
            }
            else if (raiseEventOptions.Receivers == ReceiverGroup.MasterClient)
            {
                muninnRaiseEventOptions.Target = RaiseEventTarget.TO_MASTER;
            }
        }

        #endregion

        MuninnNetwork.RaiseEvent(data, muninnRaiseEventOptions);

        if (raiseEventOptions?.CachingOption == EventCaching.AddToRoomCache)
        {
            MuninnNetwork.AddCodedCache(eventCode, contentBytes, false);
        }
        else if (raiseEventOptions?.CachingOption == EventCaching.AddToRoomCacheGlobal)
        {
            MuninnNetwork.AddCodedCache(eventCode, contentBytes);
        }

        return true;
    }
}