﻿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 UnityEngine;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using MuninnRaiseEventOptions = Unity.Muninn.Model.RaiseEventOptions;


internal partial class MuninnPeer
{
    private uint _previousMasterId;

    private byte _lastJoinOperationCode;

    private void OnEncryptionEstablished()
    {
        Listener.OnStatusChanged(StatusCode.EncryptionEstablished);
    }

    private void OnConnected()
    {
        PeerState = PeerStateValue.Connected;
        Listener.OnStatusChanged(StatusCode.Connect);
    }

    private void OnGetRoomByName(QueryRoomResponse response)
    {
        if (response.Code == (uint)MuninnCode.LobbyQueryRoomFailed)
        {
            Listener.OnOperationResponse(new OperationResponse
            {
                OperationCode = OperationCode.JoinGame,
                Parameters = new Dictionary<byte, object>(),
                ReturnCode = ErrorCode.InternalServerError,
                DebugMessage = ErrorMessages.InternalError
            });
            return;
        }

        if (response.Code == (uint)MuninnCode.LobbyRoomUnknown || response.Status == MuninnLobbyRoomStatus.Closed)
        {
            Listener.OnOperationResponse(new OperationResponse
            {
                OperationCode = OperationCode.JoinGame,
                Parameters = new Dictionary<byte, object>(),
                ReturnCode = ErrorCode.GameDoesNotExist,
                DebugMessage = ErrorMessages.GameIdDoesNotExist
            });
            return;
        }

        MuninnNetwork.JoinRoom(new JoinRoomRequest
        {
            RoomUuid = response.RoomUuid
        });
    }

    private void OnListRooms(ListRoomResponse response)
    {
        var rooms = response.Items.Where(room => room.PlayerCount > 0).ToList();
        var data = new Hashtable();
        rooms.ForEach(room =>
        {
            var roomInfo = new Hashtable
            {
                [GamePropertyKey.MaxPlayers] = (byte)room.MaxPlayers,
                [GamePropertyKey.PlayerCount] = (byte)room.PlayerCount,
                [GamePropertyKey.IsVisible] = room.Visibility is MuninnRoomVisibility.Public,
                [GamePropertyKey.IsOpen] =
                    room.Status == MuninnLobbyRoomStatus.Ready
            };
            roomInfo.TryAddParameters(room.CustomProperties);
            data[room.RoomUuid] = roomInfo;
        });
        var eventData = new EventData
        {
            Code = EventCode.GameList,
            Parameters = new Dictionary<byte, object>
            {
                [ParameterCode.GameList] = data
            }
        };
        Listener.OnEvent(eventData);

        // var statsEvent = new EventData
        // {
        //     Code = EventCode.AppStats,
        //     Parameters = new Dictionary<byte, object>
        //     {
        //         [ParameterCode.MasterPeerCount] = 0,
        //         [ParameterCode.PeerCount] = (int)rooms.Sum(room => room.PlayerCount),
        //         [ParameterCode.GameCount] = rooms.Count
        //     }
        // };
        //
        // Listener.OnEvent(statsEvent);
    }

    private void OnJoinedRoom(MuninnRoomView room)
    {
        if (Client.enterRoomParamsCache != null)
        {
            Client.enterRoomParamsCache.RoomName = room.Room.Id;
        }

        var roomInfo = room.Room;
        var players = room.Players;
        var gameProperties = new Hashtable
        {
            [GamePropertyKey.MaxPlayers] = (byte)roomInfo.MaxPlayers,
            [GamePropertyKey.PlayerCount] = (byte)players.Count,
            [GamePropertyKey.IsVisible] = roomInfo.Visibility is MuninnRoomVisibility.Public,
            [GamePropertyKey.MasterClientId] = (int)room.MasterClientId,
            [GamePropertyKey.IsOpen] = true,
        };
        gameProperties.TryAddParameters(roomInfo.Properties);

        var actorProperties = new Hashtable();
        players.ForEach(player =>
        {
            var playerProperties = new Hashtable
            {
                [ActorProperties.UserId] = player.Id,
                [ActorProperties.PlayerName] = player.Name,
                [ActorProperties.IsInactive] = false,
            };
            playerProperties.TryAddParameters(player.Properties);
            actorProperties[(int)player.SenderId] = playerProperties;
        });

        var response = new OperationResponse
        {
            OperationCode = _lastJoinOperationCode,
            Parameters = new Dictionary<byte, object>
            {
                [ParameterCode.ActorNr] = (int)room.SenderId,
                [ParameterCode.ActorList] = players.Select(p => (int)p.SenderId).ToArray(),
                [ParameterCode.GameProperties] = gameProperties,
                [ParameterCode.PlayerProperties] = actorProperties,
            }
        };

        Listener.OnOperationResponse(response);
    }

    private void OnPlayerEnteredRoom(MuninnPlayer player)
    {
        var playerProperties = new Hashtable
        {
            [ActorProperties.UserId] = player.Id,
            [ActorProperties.IsInactive] = false,
            [ActorProperties.PlayerName] = player.Name
        };
        playerProperties.TryAddParameters(player.Properties);

        var eventData = new EventData
        {
            Code = EventCode.Join,
            Parameters = new Dictionary<byte, object>
            {
                [ParameterCode.ActorList] = new[] { (int)player.SenderId },
                [ParameterCode.PlayerProperties] = playerProperties,
                [ParameterCode.ActorNr] = (int)player.SenderId
            }
        };
        Listener.OnEvent(eventData);
    }

    private void OnUpdatePlayerInfo(MuninnUpdatePlayerResponse updatePlayerResponse, bool needBack = false)
    {
        var response = new OperationResponse
        {
            OperationCode = OperationCode.SetProperties,
            Parameters = new Dictionary<byte, object>()
        };
        Listener.OnOperationResponse(response);
        if (needBack)
        {
            OnPlayerInfoUpdated(updatePlayerResponse.Player);
        }
    }

    private void OnUpdateRoomCustomProperties(MuninnUpdateRoomCustomPropertiesResponse customPropertiesResponse,
        bool needBack = false)
    {
        var response = new OperationResponse
        {
            OperationCode = OperationCode.SetProperties,
            Parameters = new Dictionary<byte, object>()
        };
        Listener.OnOperationResponse(response);
        if (needBack)
        {
            OnRoomCustomPropertiesUpdated(customPropertiesResponse.Properties);
        }
    }

    private void OnPlayerInfoUpdated(MuninnPlayer player)
    {
        var photonPlayer = Client.GetPlayerWithId((int)player.SenderId);
        var diff = player.Properties.Diff(photonPlayer.CustomProperties);
        if (player.Name != photonPlayer.NickName)
        {
            diff.Add(ActorProperties.PlayerName, player.Name);
        }

        var eventData = new EventData
        {
            Code = EventCode.PropertiesChanged,
            Parameters = new Dictionary<byte, object>
            {
                [ParameterCode.TargetActorNr] = (int)player.SenderId,
                [ParameterCode.Properties] = diff,
                [ParameterCode.ActorNr] = 0
            }
        };
        Listener.OnEvent(eventData);
    }

    private void OnRoomCustomPropertiesUpdated(Dictionary<string, string> customProperties)
    {
        var photonRoom = Client.CurrentRoom;
        var diff = customProperties.Diff(photonRoom.CustomProperties);
        var eventData = new EventData
        {
            Code = EventCode.PropertiesChanged,
            Parameters = new Dictionary<byte, object>
            {
                { ParameterCode.TargetActorNr, 0 },
                { ParameterCode.Properties, diff },
                { ParameterCode.ActorNr, 0 }
            }
        };
        Listener.OnEvent(eventData);
    }

    private void OnLeftRoom(LeaveRoomEvent leaveRoomEvent)
    {
        var response = new OperationResponse
        {
            OperationCode = OperationCode.Leave,
            Parameters = new Dictionary<byte, object>()
        };
        Listener.OnOperationResponse(response);
    }

    private void OnDisconnected()
    {
        PeerState = PeerStateValue.Disconnected;
        Listener.OnStatusChanged(StatusCode.Disconnect);
    }

    private void OnCustomEventArrived(MuninnEvent muninnEvent)
    {
        var eventHashtable = (Hashtable)SerializationUtil.Deserialize(muninnEvent.Data) ?? new Hashtable();
        var eventData = new EventData
        {
            Code = (byte)eventHashtable[ParameterCode.Code],
            Parameters = new Dictionary<byte, object>
            {
                { ParameterCode.Data, eventHashtable[ParameterCode.Data] },
                { ParameterCode.ActorNr, (int)muninnEvent.SenderId }
            }
        };
        Listener.OnEvent(eventData);
    }

    private void OnCacheSliceChanged(int slice, uint senderId)
    {
        var eventData = new EventData
        {
            Code = EventCode.CacheSliceChanged,
            Parameters = new Dictionary<byte, object>
            {
                { ParameterCode.CacheSliceIndex, slice },
                { ParameterCode.ActorNr, (int)senderId }
            }
        };
        Listener.OnEvent(eventData);
    }

    private void OnSlicedCacheReceived(SortedDictionary<int, IEnumerable<CodedEvent>> slicedCacheResponse)
    {
        foreach (var (slice, events) in slicedCacheResponse)
        {
            if (slice != 0)
            {
                OnCacheSliceChanged(slice, 0);
            }

            foreach (var codedEvent in events)
            {
                var codedEventData = new EventData
                {
                    Code = codedEvent.Code,
                    Parameters = new Dictionary<byte, object>
                    {
                        { ParameterCode.ActorNr, (int)codedEvent.SenderId }
                    }
                };
                if (codedEvent.Data != null)
                {
                    codedEventData.Parameters.Add(ParameterCode.Data,
                        SerializationUtil.Deserialize(codedEvent.Data));
                }

                Listener.OnEvent(codedEventData);
            }
        }
    }

    private void OnPlayerLeftRoom(MuninnPlayer player)
    {
        // 若为房主退出，等待MasterClientChanged事件
        if (player.SenderId == _muninnPeerBehaviour.GetMuninnRoomView().MasterClientId)
        {
            _previousMasterId = player.SenderId;
        }
        else
        {
            var @event = new EventData
            {
                Code = EventCode.Leave,
                Parameters = new Dictionary<byte, object>
                {
                    { ParameterCode.ActorNr, (int)player.SenderId }
                }
            };
            Listener.OnEvent(@event);
        }
    }

    private void OnMasterClientChanged(uint masterClientId)
    {
        if (_previousMasterId == 0)
            return;
        var @event = new EventData
        {
            Code = EventCode.Leave,
            Parameters = new Dictionary<byte, object>
            {
                { ParameterCode.ActorNr, (int)_previousMasterId },
                { ParameterCode.MasterClientId, (int)masterClientId }
            }
        };
        _previousMasterId = 0;
        Listener.OnEvent(@event);
    }

    private void OnJoinRoomFailed(MuninnError error)
    {
        var response = new OperationResponse
        {
            Parameters = new Dictionary<byte, object>(),
            OperationCode = _lastJoinOperationCode
        };
        switch ((MuninnCode)error.Code)
        {
            case MuninnCode.MismatchedAppId:
            case MuninnCode.InvalidClientAppId:
            case MuninnCode.InvalidClientAppSecret:
            case MuninnCode.InvalidClientPlayerId:
            case MuninnCode.LobbyAccessDenied:
            case MuninnCode.LobbyAuthenticationFailed:
            case MuninnCode.LobbyMissingAuthToken:
                response.ReturnCode = ErrorCode.InvalidAuthentication;
                response.DebugMessage = ErrorMessages.AuthTokenInvalid;
                break;

            case MuninnCode.LobbyRoomNameAlreadyExisted:
                response.ReturnCode = ErrorCode.GameIdAlreadyExists;
                response.DebugMessage = ErrorMessages.GameAlreadyExist;
                break;

            case MuninnCode.LobbyCreateRoomLimitExceeded:
                response.ReturnCode = ErrorCode.ServerFull;
                response.DebugMessage = ErrorMessages.InternalError;
                break;

            case MuninnCode.MaxPlayersExceeded:
                response.ReturnCode = ErrorCode.GameFull;
                response.DebugMessage = ErrorMessages.GameFull;
                break;

            case MuninnCode.LobbyRoomClosed:
            case MuninnCode.RoomClosed:
                response.ReturnCode = ErrorCode.GameClosed;
                response.DebugMessage = ErrorMessages.GameClosed;
                break;
            case MuninnCode.LobbyRoomUnknown:
                response.ReturnCode = ErrorCode.GameDoesNotExist;
                response.ReturnCode = ErrorCode.GameDoesNotExist;
                break;

            case MuninnCode.LobbyJoinRoomFailed:
                response.ReturnCode = ErrorCode.InternalServerError;
                response.DebugMessage = ErrorMessages.InternalError;
                break;

            case MuninnCode.MissingJoinCode:
            case MuninnCode.InvalidJoinCode:
                response.ReturnCode = ErrorCode.OperationNotAllowedInCurrentState;
                response.ReturnCode = ErrorCode.OperationNotAllowedInCurrentState;
                break;

            case MuninnCode.InvalidParam:
            case MuninnCode.LobbyCreateRoomFailed:
            case MuninnCode.InternalServerError:
            case MuninnCode.OperationFailed:
            case MuninnCode.PlayerJoinedAnotherRoom:
            case MuninnCode.ConnectionFailed:
            case MuninnCode.UserReLoggedIn:
            case MuninnCode.UnexpectedRoomError:
            case MuninnCode.ClientTimedOut:
            case MuninnCode.LobbyQueryRoomFailed:
            case MuninnCode.LobbyCloseRoomFailed:
            default:
                response.ReturnCode = ErrorCode.InternalServerError;
                response.DebugMessage = ErrorMessages.InternalError;
                break;
        }

        Listener.OnOperationResponse(response);
    }

    private void OnQueryRandomRoom(ListRoomResponse response, OpJoinRandomRoomParams opJoinRandomRoomParams)
    {
        var toJoin =
            response.Items.FirstOrDefault(room =>
            {
                if (room.Visibility != MuninnRoomVisibility.Public)
                {
                    return false;
                }

                if (room.Status != MuninnLobbyRoomStatus.Ready)
                {
                    return false;
                }

                if (room.PlayerCount == 0 || room.PlayerCount >= room.MaxPlayers)
                {
                    return false;
                }

                if (opJoinRandomRoomParams.ExpectedMaxPlayers > 0 &&
                    room.MaxPlayers != opJoinRandomRoomParams.ExpectedMaxPlayers)
                {
                    return false;
                }

                if (opJoinRandomRoomParams.ExpectedCustomRoomProperties != null &&
                    opJoinRandomRoomParams.ExpectedCustomRoomProperties.Any())
                {
                    var currentProperties = room.CustomProperties.ToHashtable();
                    if (currentProperties == null)
                    {
                        return false;
                    }

                    foreach (var entry in opJoinRandomRoomParams.ExpectedCustomRoomProperties)
                    {
                        if (!currentProperties.TryGetValue(entry.Key, out var value) || !value.Equals(entry.Value))
                        {
                            return false;
                        }
                    }
                }

                return true;
            });
        var result = new OperationResponse
        {
            OperationCode = OperationCode.JoinRandomGame,
            Parameters = new Dictionary<byte, object>()
        };
        if (toJoin == default)
        {
            result.ReturnCode = ErrorCode.NoRandomMatchFound;
            result.DebugMessage = ErrorMessages.NoMatchFound;
        }
        else
        {
            result.Parameters.Add(ParameterCode.RoomName, toJoin.RoomUuid);
            result.Parameters.Add(ParameterCode.Address, ServerAddress ?? MuninnSettings.LobbyDomain);
        }

        Listener.OnOperationResponse(result);
    }

    private IEnumerator PingServer()
    {
        var sock = new Ping(UosIP);
        var tries = 0;
        while (!sock.isDone && tries < 20)
        {
            ++tries;
            yield return new WaitForSeconds(0.1f);
        }

        yield return sock.isDone;
    }

    private void SetupBehaviour()
    {
        if (_muninnPeerBehaviour)
            return;

        _muninnPeerBehaviour = new GameObject("muninnPeerBehaviour").AddComponent<MuninnPeerBehaviour>();
        _muninnPeerBehaviour.JoinedRoom = OnJoinedRoom;
        _muninnPeerBehaviour.PlayerEnteredRoom = OnPlayerEnteredRoom;
        _muninnPeerBehaviour.PlayerInfoUpdated = OnPlayerInfoUpdated;
        _muninnPeerBehaviour.RoomCustomPropertiesUpdated = OnRoomCustomPropertiesUpdated;
        _muninnPeerBehaviour.LeftRoom = OnLeftRoom;
        _muninnPeerBehaviour.Disconnected = OnDisconnected;
        _muninnPeerBehaviour.CustomEventArrived = OnCustomEventArrived;
        _muninnPeerBehaviour.CacheSliceChanged = OnCacheSliceChanged;
        _muninnPeerBehaviour.SlicedCacheReceived = OnSlicedCacheReceived;
        _muninnPeerBehaviour.JoinRoomFailed = OnJoinRoomFailed;
        _muninnPeerBehaviour.PlayerLeftRoom = OnPlayerLeftRoom;
        _muninnPeerBehaviour.MasterClientChanged = OnMasterClientChanged;
    }
}