package net.pokeranalytics.android

import android.app.Application
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.RealmResults
import io.realm.kotlin.where
import net.pokeranalytics.android.model.realm.Game
import net.pokeranalytics.android.model.realm.Session
import net.pokeranalytics.android.util.PokerAnalyticsLogs
import timber.log.Timber
import java.util.*


class PokerAnalyticsApplication : Application() {

	var sessions: RealmResults<Session>? = null

//    private val listener: OrderedRealmCollectionChangeListener<RealmResults<Session>> =
//        OrderedRealmCollectionChangeListener() { realmResults: RealmResults<Session>, changeSet: OrderedCollectionChangeSet ->
//
//            if (changeSet == null) {
//                return@OrderedRealmCollectionChangeListener
//            }
//
//            val realm: Realm = Realm.getDefaultInstance()
//
//            val deletedSessions = realm.where(Session::class.java).`in`("id", changeSet.deletions.toTypedArray()).findAll()
//            deletedSessions.forEach { it.cleanup() }
//
//    }

	override fun onCreate() {
		super.onCreate()

		// Realm
		Realm.init(this)
		val realmConfiguration = RealmConfiguration.Builder()
			.name(Realm.DEFAULT_REALM_NAME)
			.deleteRealmIfMigrationNeeded()
			.build()
		Realm.setDefaultConfiguration(realmConfiguration)

		val realm: Realm = Realm.getDefaultInstance()
		// Add observer on session time frame changes
		this.sessions = realm.where(Session::class.java).findAll() // monitor session deletions
		this.sessions?.addChangeListener { t, changeSet ->
			/*
			val deletedSessions =
				realm.where(Session::class.java).`in`("id", changeSet.deletions.toTypedArray()).findAll()
			deletedSessions.forEach { it.cleanup() }
			*/
		}

		if (BuildConfig.DEBUG) {
			// Logs
			Timber.plant(PokerAnalyticsLogs())
		} else {
			//Fabric.with(this, Crashlytics())
		}

		if (BuildConfig.DEBUG) {
			createDefaultData()
		}

	}

	/**
	 * Create default data
	 */
	private fun createDefaultData() {

		val gamesName = resources.getStringArray(R.array.game_name)
		val gamesShortName = resources.getStringArray(R.array.game_short_name)

		val realm = Realm.getDefaultInstance()
		if (realm.where<Game>().findAll().isEmpty()) {
			realm.executeTransaction {
				for ((index, name) in gamesName.withIndex()) {
					val game = Game()
					game.id = UUID.randomUUID().toString()
					game.name = name
					game.shortName = gamesShortName[index]
					realm.copyToRealmOrUpdate(game)
				}
			}
		}

	}

}