package com.ponzischeme89.memby.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test

class ProfileViewModelStoreOwnerTest {
    private val factory = object : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST")
        override fun <T : ViewModel> create(modelClass: Class<T>): T =
            ProbeViewModel() as T
    }

    @Test
    fun `profiles have isolated view models and clearing cancels the old one`() {
        val mattOwner = ProfileViewModelStoreOwner()
        val familyOwner = ProfileViewModelStoreOwner()

        val matt = ViewModelProvider(mattOwner, factory)[ProbeViewModel::class.java]
        val mattAgain = ViewModelProvider(mattOwner, factory)[ProbeViewModel::class.java]
        val family = ViewModelProvider(familyOwner, factory)[ProbeViewModel::class.java]

        assertSame(matt, mattAgain)
        assertNotSame(matt, family)
        assertFalse(matt.cleared)
        assertFalse(family.cleared)

        mattOwner.clear()

        assertTrue(matt.cleared)
        assertFalse(family.cleared)
    }

    private class ProbeViewModel : ViewModel() {
        var cleared = false
            private set

        override fun onCleared() {
            cleared = true
        }
    }
}
