/**
 * Standalone signaling server for the Nextcloud Spreed app.
 * Copyright (C) 2019 struktur AG
 *
 * @author Joachim Bauch <bauch@struktur.de>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package signaling

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestVirtualSession(t *testing.T) {
	t.Parallel()
	CatchLogForTest(t)
	require := require.New(t)
	assert := assert.New(t)
	hub, _, _, server := CreateHubForTest(t)

	roomId := "the-room-id"
	emptyProperties := json.RawMessage("{}")
	backend := &Backend{
		id:     "compat",
		compat: true,
	}
	room, err := hub.createRoom(roomId, emptyProperties, backend)
	require.NoError(err)
	defer room.Close()

	clientInternal := NewTestClient(t, server, hub)
	defer clientInternal.CloseWithBye()
	require.NoError(clientInternal.SendHelloInternal())

	client := NewTestClient(t, server, hub)
	defer client.CloseWithBye()
	require.NoError(client.SendHello(testDefaultUserId))

	ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
	defer cancel()

	if hello, err := clientInternal.RunUntilHello(ctx); assert.NoError(err) {
		assert.Empty(hello.Hello.UserId)
		assert.NotEmpty(hello.Hello.SessionId)
		assert.NotEmpty(hello.Hello.ResumeId)
	}
	hello, err := client.RunUntilHello(ctx)
	assert.NoError(err)

	roomMsg, err := client.JoinRoom(ctx, roomId)
	require.NoError(err)
	require.Equal(roomId, roomMsg.Room.RoomId)

	// Ignore "join" events.
	assert.NoError(client.DrainMessages(ctx))

	internalSessionId := "session1"
	userId := "user1"
	msgAdd := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "addsession",
			AddSession: &AddSessionInternalClientMessage{
				CommonSessionInternalClientMessage: CommonSessionInternalClientMessage{
					SessionId: internalSessionId,
					RoomId:    roomId,
				},
				UserId: userId,
				Flags:  FLAG_MUTED_SPEAKING,
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgAdd))

	msg1, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	// The public session id will be generated by the server, so don't check for it.
	require.NoError(client.checkMessageJoinedSession(msg1, "", userId))
	sessionId := msg1.Event.Join[0].SessionId
	session := hub.GetSessionByPublicId(sessionId)
	if assert.NotNil(session, "Could not get virtual session %s", sessionId) {
		assert.Equal(HelloClientTypeVirtual, session.ClientType())
		sid := session.(*VirtualSession).SessionId()
		assert.Equal(internalSessionId, sid)
	}

	// Also a participants update event will be triggered for the virtual user.
	msg2, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	if updateMsg, err := checkMessageParticipantsInCall(msg2); assert.NoError(err) {
		assert.Equal(roomId, updateMsg.RoomId)
		if assert.Len(updateMsg.Users, 1) {
			assert.Equal(sessionId, updateMsg.Users[0]["sessionId"])
			assert.Equal(true, updateMsg.Users[0]["virtual"])
			assert.EqualValues((FlagInCall | FlagWithPhone), updateMsg.Users[0]["inCall"])
		}
	}

	msg3, err := client.RunUntilMessage(ctx)
	require.NoError(err)

	if flagsMsg, err := checkMessageParticipantFlags(msg3); assert.NoError(err) {
		assert.Equal(roomId, flagsMsg.RoomId)
		assert.Equal(sessionId, flagsMsg.SessionId)
		assert.EqualValues(FLAG_MUTED_SPEAKING, flagsMsg.Flags)
	}

	newFlags := uint32(FLAG_TALKING)
	msgFlags := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "updatesession",
			UpdateSession: &UpdateSessionInternalClientMessage{
				CommonSessionInternalClientMessage: CommonSessionInternalClientMessage{
					SessionId: internalSessionId,
					RoomId:    roomId,
				},
				Flags: &newFlags,
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgFlags))

	msg4, err := client.RunUntilMessage(ctx)
	require.NoError(err)

	if flagsMsg, err := checkMessageParticipantFlags(msg4); assert.NoError(err) {
		assert.Equal(roomId, flagsMsg.RoomId)
		assert.Equal(sessionId, flagsMsg.SessionId)
		assert.EqualValues(newFlags, flagsMsg.Flags)
	}

	// A new client will receive the initial flags of the virtual session.
	client2 := NewTestClient(t, server, hub)
	defer client2.CloseWithBye()
	require.NoError(client2.SendHello(testDefaultUserId + "2"))

	_, err = client2.RunUntilHello(ctx)
	require.NoError(err)

	roomMsg, err = client2.JoinRoom(ctx, roomId)
	require.NoError(err)
	require.Equal(roomId, roomMsg.Room.RoomId)

	gotFlags := false
	var receivedMessages []*ServerMessage
	for !gotFlags {
		messages, err := client2.GetPendingMessages(ctx)
		if err != nil {
			assert.NoError(err)
			if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
				break
			}
		}

		receivedMessages = append(receivedMessages, messages...)
		for _, msg := range messages {
			if msg.Type != "event" || msg.Event.Target != "participants" || msg.Event.Type != "flags" {
				continue
			}

			if assert.Equal(roomId, msg.Event.Flags.RoomId) &&
				assert.Equal(sessionId, msg.Event.Flags.SessionId) &&
				assert.EqualValues(newFlags, msg.Event.Flags.Flags) {
				gotFlags = true
				break
			}
		}
	}
	assert.True(gotFlags, "Didn't receive initial flags in %+v", receivedMessages)

	// Ignore "join" messages from second client
	assert.NoError(client.DrainMessages(ctx))

	// When sending to a virtual session, the message is sent to the actual
	// client and contains a "Recipient" block with the internal session id.
	recipient := MessageClientMessageRecipient{
		Type:      "session",
		SessionId: sessionId,
	}

	data := "from-client-to-virtual"
	require.NoError(client.SendMessage(recipient, data))

	msg2, err = clientInternal.RunUntilMessage(ctx)
	require.NoError(err)
	require.NoError(checkMessageType(msg2, "message"))
	require.NoError(checkMessageSender(hub, msg2.Message.Sender, "session", hello.Hello))

	if assert.NotNil(msg2.Message.Recipient) {
		assert.Equal("session", msg2.Message.Recipient.Type)
		assert.Equal(internalSessionId, msg2.Message.Recipient.SessionId)
	}

	var payload string
	if err := json.Unmarshal(msg2.Message.Data, &payload); assert.NoError(err) {
		assert.Equal(data, payload)
	}

	msgRemove := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "removesession",
			RemoveSession: &RemoveSessionInternalClientMessage{
				CommonSessionInternalClientMessage: CommonSessionInternalClientMessage{
					SessionId: internalSessionId,
					RoomId:    roomId,
				},
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgRemove))

	if msg5, err := client.RunUntilMessage(ctx); assert.NoError(err) {
		assert.NoError(client.checkMessageRoomLeaveSession(msg5, sessionId))
	}
}

func checkHasEntryWithInCall(message *RoomEventServerMessage, sessionId string, entryType string, inCall int) error {
	found := false
	for _, entry := range message.Users {
		if sid, ok := entry["sessionId"].(string); ok && sid == sessionId {
			if value, ok := entry[entryType].(bool); !ok || !value {
				return fmt.Errorf("Expected %s user, got %+v", entryType, entry)
			}

			if value, ok := entry["inCall"].(float64); !ok || int(value) != inCall {
				return fmt.Errorf("Expected in call %d, got %+v", inCall, entry)
			}
			found = true
			break
		}
	}

	if !found {
		return fmt.Errorf("No user with session id %s found, got %+v", sessionId, message)
	}

	return nil
}

func TestVirtualSessionCustomInCall(t *testing.T) {
	t.Parallel()
	CatchLogForTest(t)
	require := require.New(t)
	assert := assert.New(t)
	hub, _, _, server := CreateHubForTest(t)

	roomId := "the-room-id"
	emptyProperties := json.RawMessage("{}")
	backend := &Backend{
		id:     "compat",
		compat: true,
	}
	room, err := hub.createRoom(roomId, emptyProperties, backend)
	require.NoError(err)
	defer room.Close()

	clientInternal := NewTestClient(t, server, hub)
	defer clientInternal.CloseWithBye()
	features := []string{
		ClientFeatureInternalInCall,
	}
	require.NoError(clientInternal.SendHelloInternalWithFeatures(features))

	client := NewTestClient(t, server, hub)
	defer client.CloseWithBye()
	require.NoError(client.SendHello(testDefaultUserId))

	ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
	defer cancel()

	helloInternal, err := clientInternal.RunUntilHello(ctx)
	if assert.NoError(err) {
		assert.Empty(helloInternal.Hello.UserId)
		assert.NotEmpty(helloInternal.Hello.SessionId)
		assert.NotEmpty(helloInternal.Hello.ResumeId)
	}
	roomMsg, err := clientInternal.JoinRoomWithRoomSession(ctx, roomId, "")
	require.NoError(err)
	require.Equal(roomId, roomMsg.Room.RoomId)

	hello, err := client.RunUntilHello(ctx)
	assert.NoError(err)
	roomMsg, err = client.JoinRoom(ctx, roomId)
	require.NoError(err)
	require.Equal(roomId, roomMsg.Room.RoomId)

	if _, additional, err := clientInternal.RunUntilJoinedAndReturn(ctx, helloInternal.Hello, hello.Hello); assert.NoError(err) {
		if assert.Len(additional, 1) && assert.Equal("event", additional[0].Type) {
			assert.Equal("participants", additional[0].Event.Target)
			assert.Equal("update", additional[0].Event.Type)
			assert.Equal(helloInternal.Hello.SessionId, additional[0].Event.Update.Users[0]["sessionId"])
			assert.EqualValues(0, additional[0].Event.Update.Users[0]["inCall"])
		}
	}
	assert.NoError(client.RunUntilJoined(ctx, helloInternal.Hello, hello.Hello))

	internalSessionId := "session1"
	userId := "user1"
	msgAdd := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "addsession",
			AddSession: &AddSessionInternalClientMessage{
				CommonSessionInternalClientMessage: CommonSessionInternalClientMessage{
					SessionId: internalSessionId,
					RoomId:    roomId,
				},
				UserId: userId,
				Flags:  FLAG_MUTED_SPEAKING,
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgAdd))

	msg1, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	// The public session id will be generated by the server, so don't check for it.
	require.NoError(client.checkMessageJoinedSession(msg1, "", userId))
	sessionId := msg1.Event.Join[0].SessionId
	session := hub.GetSessionByPublicId(sessionId)
	if assert.NotNil(session) {
		assert.Equal(HelloClientTypeVirtual, session.ClientType())
		sid := session.(*VirtualSession).SessionId()
		assert.Equal(internalSessionId, sid)
	}

	// Also a participants update event will be triggered for the virtual user.
	msg2, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	if updateMsg, err := checkMessageParticipantsInCall(msg2); assert.NoError(err) {
		assert.Equal(roomId, updateMsg.RoomId)
		assert.Len(updateMsg.Users, 2)

		assert.NoError(checkHasEntryWithInCall(updateMsg, sessionId, "virtual", 0))
		assert.NoError(checkHasEntryWithInCall(updateMsg, helloInternal.Hello.SessionId, "internal", 0))
	}

	msg3, err := client.RunUntilMessage(ctx)
	require.NoError(err)

	if flagsMsg, err := checkMessageParticipantFlags(msg3); assert.NoError(err) {
		assert.Equal(roomId, flagsMsg.RoomId)
		assert.Equal(sessionId, flagsMsg.SessionId)
		assert.EqualValues(FLAG_MUTED_SPEAKING, flagsMsg.Flags)
	}

	// The internal session can change its "inCall" flags
	msgInCall := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "incall",
			InCall: &InCallInternalClientMessage{
				InCall: FlagInCall | FlagWithAudio,
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgInCall))

	msg4, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	if updateMsg, err := checkMessageParticipantsInCall(msg4); assert.NoError(err) {
		assert.Equal(roomId, updateMsg.RoomId)
		assert.Len(updateMsg.Users, 2)
		assert.NoError(checkHasEntryWithInCall(updateMsg, sessionId, "virtual", 0))
		assert.NoError(checkHasEntryWithInCall(updateMsg, helloInternal.Hello.SessionId, "internal", FlagInCall|FlagWithAudio))
	}

	// The internal session can change the "inCall" flags of a virtual session
	newInCall := FlagInCall | FlagWithPhone
	msgInCall2 := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "updatesession",
			UpdateSession: &UpdateSessionInternalClientMessage{
				CommonSessionInternalClientMessage: CommonSessionInternalClientMessage{
					SessionId: internalSessionId,
					RoomId:    roomId,
				},
				InCall: &newInCall,
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgInCall2))

	msg5, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	if updateMsg, err := checkMessageParticipantsInCall(msg5); assert.NoError(err) {
		assert.Equal(roomId, updateMsg.RoomId)
		assert.Len(updateMsg.Users, 2)
		assert.NoError(checkHasEntryWithInCall(updateMsg, sessionId, "virtual", newInCall))
		assert.NoError(checkHasEntryWithInCall(updateMsg, helloInternal.Hello.SessionId, "internal", FlagInCall|FlagWithAudio))
	}
}

func TestVirtualSessionCleanup(t *testing.T) {
	t.Parallel()
	CatchLogForTest(t)
	require := require.New(t)
	assert := assert.New(t)
	hub, _, _, server := CreateHubForTest(t)

	roomId := "the-room-id"
	emptyProperties := json.RawMessage("{}")
	backend := &Backend{
		id:     "compat",
		compat: true,
	}
	room, err := hub.createRoom(roomId, emptyProperties, backend)
	require.NoError(err)
	defer room.Close()

	clientInternal := NewTestClient(t, server, hub)
	defer clientInternal.CloseWithBye()
	require.NoError(clientInternal.SendHelloInternal())

	client := NewTestClient(t, server, hub)
	defer client.CloseWithBye()
	require.NoError(client.SendHello(testDefaultUserId))

	ctx, cancel := context.WithTimeout(context.Background(), testTimeout)
	defer cancel()

	if hello, err := clientInternal.RunUntilHello(ctx); assert.NoError(err) {
		assert.Empty(hello.Hello.UserId)
		assert.NotEmpty(hello.Hello.SessionId)
		assert.NotEmpty(hello.Hello.ResumeId)
	}
	_, err = client.RunUntilHello(ctx)
	assert.NoError(err)

	roomMsg, err := client.JoinRoom(ctx, roomId)
	require.NoError(err)
	require.Equal(roomId, roomMsg.Room.RoomId)

	// Ignore "join" events.
	assert.NoError(client.DrainMessages(ctx))

	internalSessionId := "session1"
	userId := "user1"
	msgAdd := &ClientMessage{
		Type: "internal",
		Internal: &InternalClientMessage{
			Type: "addsession",
			AddSession: &AddSessionInternalClientMessage{
				CommonSessionInternalClientMessage: CommonSessionInternalClientMessage{
					SessionId: internalSessionId,
					RoomId:    roomId,
				},
				UserId: userId,
				Flags:  FLAG_MUTED_SPEAKING,
			},
		},
	}
	require.NoError(clientInternal.WriteJSON(msgAdd))

	msg1, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	// The public session id will be generated by the server, so don't check for it.
	require.NoError(client.checkMessageJoinedSession(msg1, "", userId))
	sessionId := msg1.Event.Join[0].SessionId
	session := hub.GetSessionByPublicId(sessionId)
	if assert.NotNil(session) {
		assert.Equal(HelloClientTypeVirtual, session.ClientType())
		sid := session.(*VirtualSession).SessionId()
		assert.Equal(internalSessionId, sid)
	}

	// Also a participants update event will be triggered for the virtual user.
	msg2, err := client.RunUntilMessage(ctx)
	require.NoError(err)
	if updateMsg, err := checkMessageParticipantsInCall(msg2); assert.NoError(err) {
		assert.Equal(roomId, updateMsg.RoomId)
		if assert.Len(updateMsg.Users, 1) {
			assert.Equal(sessionId, updateMsg.Users[0]["sessionId"])
			assert.Equal(true, updateMsg.Users[0]["virtual"])
			assert.EqualValues((FlagInCall | FlagWithPhone), updateMsg.Users[0]["inCall"])
		}
	}

	msg3, err := client.RunUntilMessage(ctx)
	require.NoError(err)

	if flagsMsg, err := checkMessageParticipantFlags(msg3); assert.NoError(err) {
		assert.Equal(roomId, flagsMsg.RoomId)
		assert.Equal(sessionId, flagsMsg.SessionId)
		assert.EqualValues(FLAG_MUTED_SPEAKING, flagsMsg.Flags)
	}

	// The virtual sessions are closed when the parent session is deleted.
	clientInternal.CloseWithBye()

	msg2, err = client.RunUntilMessage(ctx)
	require.NoError(err)
	assert.NoError(client.checkMessageRoomLeaveSession(msg2, sessionId))
}
