package net.pokeranalytics.android.ui.fragment.components

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.realm.Realm
import io.realm.RealmModel
import io.realm.RealmResults

open class RealmFragment : PokerAnalyticsFragment() {

	/**
	 * A realm instance
	 */
	private lateinit var realm: Realm

	/**
	 * A List of observed RealmResults
	 */
	private var observedRealmResults: MutableList<RealmResults<*>> = mutableListOf()

	override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
		realm = Realm.getDefaultInstance()

		this.observedEntities.forEach {
			val realmResults = realm.where(it).findAll()

			realmResults.addChangeListener { _,_ ->
				this.entitiesChanged(it)
			}

			this.observedRealmResults.add(realmResults)
		}

		return super.onCreateView(inflater, container, savedInstanceState)
	}

	override fun onDestroyView() {
		super.onDestroyView()

		this.observedRealmResults.forEach {
			it.removeAllChangeListeners()
		}

		this.realm.close()
	}

	/**
	 * Get the realm instance
	 */
	fun getRealm(): Realm {
		return this.realm
	}

	/**
	 * A list of RealmModel classes to observe
	 */
	open val observedEntities: List<Class<out RealmModel>> = listOf()

	/**
	 * The method called when a change happened in any RealmResults
	 */
	open fun entitiesChanged(clazz: Class<out RealmModel>) {}

}