package net.pokeranalytics.android

import android.app.Application
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.core.CrashlyticsCore
import io.fabric.sdk.android.Fabric
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.kotlin.where
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import net.pokeranalytics.android.model.migrations.Patcher
import net.pokeranalytics.android.model.migrations.PokerAnalyticsMigration
import net.pokeranalytics.android.model.realm.Session
import net.pokeranalytics.android.model.utils.Seed
import net.pokeranalytics.android.util.FakeDataManager
import net.pokeranalytics.android.util.PokerAnalyticsLogs
import net.pokeranalytics.android.util.UserDefaults
import net.pokeranalytics.android.util.billing.AppGuard
import timber.log.Timber


class PokerAnalyticsApplication : Application() {

	override fun onCreate() {
		super.onCreate()
		UserDefaults.init(this)

		// AppGuard / Billing services
		AppGuard.load(this.applicationContext)

		// Realm
		Realm.init(this)
		val realmConfiguration = RealmConfiguration.Builder()
			.name(Realm.DEFAULT_REALM_NAME)
			.schemaVersion(6)
			.migration(PokerAnalyticsMigration())
			.initialData(Seed(this))
			.build()
		Realm.setDefaultConfiguration(realmConfiguration)

//		val realm = Realm.getDefaultInstance()
//		realm.executeTransaction {
//			realm.where(Session::class.java).findAll().deleteAllFromRealm()
//		}
//		realm.close()

		// Set up Crashlytics, disabled for debug builds
		val crashlyticsKit = Crashlytics.Builder()
			.core(CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build())
			.build()

		// Initialize Fabric with the debug-disabled crashlytics.
		Fabric.with(this, crashlyticsKit)

		if (BuildConfig.DEBUG) {
			// Logs
			Timber.plant(PokerAnalyticsLogs())
		}

		if (BuildConfig.DEBUG) {
			Timber.d("UserPreferences.defaultCurrency: ${UserDefaults.currency.symbol}")
//			this.createFakeSessions()
		}

		Patcher.patchAll(this.applicationContext)
	}

	/**
	 * Create fake sessions if we have less than 10 sessions
	 */
	private fun createFakeSessions() {

		val realm = Realm.getDefaultInstance()
		val sessionsCount = realm.where<Session>().findAll().size
		realm.close()

		if (sessionsCount < 10) {
			GlobalScope.launch {
				FakeDataManager.createFakeSessions(200)
			}
		}

	}

}