package net.pokeranalytics.android.unitTests.filter

import androidx.test.ext.junit.runners.AndroidJUnit4
import net.pokeranalytics.android.components.BaseFilterInstrumentedUnitTest
import net.pokeranalytics.android.model.filter.Query
import net.pokeranalytics.android.model.filter.QueryCondition
import net.pokeranalytics.android.model.realm.CustomField
import net.pokeranalytics.android.model.realm.CustomFieldEntry
import net.pokeranalytics.android.model.realm.Filter
import net.pokeranalytics.android.model.realm.Session
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*

@RunWith(AndroidJUnit4::class)
class CustomFieldFilterInstrumentedUnitTest : BaseFilterInstrumentedUnitTest() {

    @Test
    fun testCustomFieldListFilter() {

        val realm = this.mockRealm
        realm.beginTransaction()

        val cf1 = realm.createObject(CustomField::class.java, "1")
        cf1.type = CustomField.Type.LIST.ordinal

        val cfe1 = realm.createObject(CustomFieldEntry::class.java, "9")
        val cfe2 = realm.createObject(CustomFieldEntry::class.java, "8")
        cfe1.value = "super"
        cfe2.value = "nul"

        cf1.entries.add(cfe1)
        cf1.entries.add(cfe2)

        val s1 = Session.testInstance(100.0, false, Date(), 1)
        s1.customFieldEntries.add(cfe1)
        val s2 = Session.testInstance(100.0, true, Date(), 1)
        s2.customFieldEntries.add(cfe2)
        realm.commitTransaction()

        val sessions = Filter.queryOn<Session>(realm, Query(QueryCondition.CustomFieldListQuery(cfe2)))

        Assert.assertEquals(1, sessions.size)
        sessions[0]?.run {
            Assert.assertEquals(s2.id, (this).id)
        }
    }

    @Test
    fun testCustomFieldAmountFilter() {

        val cfId = "1234"
        var s2Id = ""

        val realm = this.mockRealm
        realm.executeTransaction {

            val cf = realm.createObject(CustomField::class.java, cfId)
            cf.type = CustomField.Type.AMOUNT.ordinal

            val cfe1 = realm.createObject(CustomFieldEntry::class.java, "999")
            cf.entries.add(cfe1)
            cfe1.numericValue = 30.0

            val cfe2 = realm.createObject(CustomFieldEntry::class.java, "888")
            cf.entries.add(cfe2)
            cfe2.numericValue = 100.0

            val s1 = Session.testInstance(100.0, false, Date(), 1)
            s1.customFieldEntries.add(cfe1)
            val s2 = Session.testInstance(100.0, true, Date(), 1)
            s2.customFieldEntries.add(cfe2)
            s2Id = s2.id
        }

        val condition = QueryCondition.CustomFieldNumberQuery(cfId, 100.0)
        val sessions = Filter.queryOn<Session>(realm, Query(condition))

        Assert.assertEquals(1, sessions.size)
        sessions.first()?.run {
            Assert.assertEquals(s2Id, this.id)
        }

    }

}