package bob.clean.data.store.cache

import bob.clean.data.model.UserInfo
import bob.clean.data.store.Cache
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verifyZeroInteractions
import org.junit.Test
import kotlin.test.*

class UserCacheImplTest {
    class TestCache : Cache {
        var key: String? = null
        var value: Any? = null
        override fun <T> save(key: String, v: T) {
            this.key = key
            value = v
        }

        @Suppress("UNCHECKED_CAST")
        override fun <T> get(key: String): T? {
            this.key = key
            return value as T?
        }
    }

    @Test
    fun testLogin() {
        val cache = TestCache()
        val userCache = UserCacheImpl(cache)

        val name = "name"
        val pass = "pass"

        assertNull(cache.value)
        assertNull(userCache.login(name, pass))

        cache.value = UserInfo(name, pass, "token")
        assertEquals(cache.value, userCache.login(name, pass))

        cache.value = UserInfo(name, "invalid pass", "token")
        assertNull(userCache.login(name, pass))
    }

    @Test
    fun testLogout() {
        val cache = mock<Cache>()
        val userCache = UserCacheImpl(cache)
        userCache.logout()
        verifyZeroInteractions(cache)
    }

    @Test
    fun testIsCachedForName() {
        val cache = TestCache()
        val userCache = UserCacheImpl(cache)

        assertNull(cache.key)
        assertFalse(userCache.isCachedForName("name"))
        assertNotNull(cache.key)

        cache.value = "value"
        assertTrue(userCache.isCachedForName("name"))
    }
}
