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.QueryCondition
import net.pokeranalytics.android.model.realm.Filter
import net.pokeranalytics.android.model.realm.Session
import net.pokeranalytics.android.ui.view.rowrepresentable.FilterCategoryRow
import net.pokeranalytics.android.ui.view.rowrepresentable.FilterSectionRow
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*

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

    @Test
    fun testSaveLoadCashFilter() {

        val realm = this.mockRealm
        realm.beginTransaction()
        val filter = Filter()
        filter.name = "testSaveLoadCashFilter"

        val filterElement = QueryCondition.IsCash
        filterElement.filterSectionRow = FilterSectionRow.CashOrTournament
        filter.createOrUpdateFilterConditions(arrayListOf(filterElement))

        val useCount = filter.countBy(FilterCategoryRow.GENERAL)
        Assert.assertEquals(1, useCount)

        val isCash = filter.contains(filterElement)
        Assert.assertEquals(true, isCash)

        val filterComponent = filter.filterConditions.first()

        filterComponent?.let {
            Assert.assertTrue(it.queryCondition is QueryCondition.IsCash)
        } ?: run {
            Assert.fail()
        }

        Session.testInstance(100.0, false, Date(), 1)
        Session.testInstance(100.0, true, Date(), 1)

        realm.copyToRealm(filter)
        realm.commitTransaction()

        val newRealm = this.mockRealm
        newRealm.where(Filter::class.java).equalTo("name", "testSaveLoadCashFilter").findFirst()?.let { foundFilter ->
            val sessions = foundFilter.results<Session>()

            Assert.assertEquals(1, sessions.size)
            sessions[0]?.run {
                Assert.assertEquals(Session.Type.CASH_GAME.ordinal, this.type)
            } ?: run {
                Assert.fail()
            }
        } ?: run {
            Assert.fail()
        }
    }
}