package net.buzzert.kordophone.backend

import net.buzzert.kordophone.backend.db.CachedChatDatabase
import net.buzzert.kordophone.backend.model.Conversation
import net.buzzert.kordophone.backend.model.Message
import org.junit.AfterClass
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.Date

class DatabaseTests {
    @Test
    fun testConversationRetrieval() {
        val db = CachedChatDatabase.testDatabase()

        val conversation = MockServer.generateConversation()
        db.writeConversations(listOf(conversation))

        val readBackConversations = db.fetchConversations()
        assertEquals(readBackConversations.count(), 1)

        val readConversation = readBackConversations[0]
        assertEquals(readConversation, conversation)

        db.close()
    }

    @Test
    fun testMessageRetrieval() {
        val db = CachedChatDatabase.testDatabase()

        val conversation = MockServer.generateConversation()
        db.writeConversations(listOf(conversation))

        var messages = listOf(
            MockServer.generateMessage(conversation),
            MockServer.generateMessage(conversation),
        )
        db.writeMessages(messages, conversation)

        val readMessages = db.fetchMessages(conversation)

        assertEquals(readMessages, messages)
        assertEquals(readMessages[0].conversation.guid, conversation.guid)

        db.close()
    }

    @Test
    fun testConversationModification() {
        val db = CachedChatDatabase.testDatabase()

        var conversation = MockServer.generateConversation().apply {
            displayName = "HooBoy"
        }

        db.writeConversations(listOf(conversation))

        val readConversation = db.fetchConversations().first()
        assertEquals(conversation.displayName, "HooBoy")

        // Change display name
        conversation.displayName = "wow"

        // Write back
        db.writeConversations(listOf(conversation))

        val nowConversations = db.fetchConversations()

        // Make sure we didn't duplicate
        assertEquals(nowConversations.count(), 1)

        // Make sure our new name was written
        assertEquals(nowConversations.first().displayName, "wow")

        db.close()
    }
}