package net.pokeranalytics.android.util

import io.realm.Realm
import io.realm.kotlin.where
import net.pokeranalytics.android.model.Limit
import net.pokeranalytics.android.model.realm.Bankroll
import net.pokeranalytics.android.model.realm.Game
import net.pokeranalytics.android.model.realm.Session
import timber.log.Timber
import java.util.*

class FakeDataManager {

	companion object {

		/**
		 * Create the given number of fake sessions
		 */
		fun createFakeSessions(numberOfSessions: Int = 1000, callback: ((success: Boolean) -> Unit)? = null) {

			val buyinList = arrayListOf(100.0, 200.0, 300.0, 500.0, 1000.0, 2000.0)
			val resultsList = arrayListOf(
				-2500.0, -2000.0, -1500.0, -1000.0, -500.0, 200.0, 1000.0, 1500.0, 2500.0, 3000.0
			)

			val commitFrequency = 100

			try {

				val realm = Realm.getDefaultInstance()
				val games = realm.where<Game>().findAll()
				val bankroll = realm.where<Bankroll>().findAll().firstOrNull()

				// Test endedSessions

				Timber.d("*** Start creating ${numberOfSessions} fake computables...")

				val s = Date()

				realm.beginTransaction()

				for (index in 1..numberOfSessions) {

					if (index % commitFrequency == 0) {
						Timber.d("****** committing at ${index} computables...")
						realm.commitTransaction()
						realm.beginTransaction()
					}

					val session = Session.newInstance(realm, Math.random() > 0.5, bankroll)

					val bigBlind = arrayListOf(1.0, 2.0, 4.0).random()
					session.cgBigBlind = bigBlind
					session.cgSmallBlind = bigBlind / 2.0

					val calendar = Calendar.getInstance()
					val twoDaysBetweenEachSession: Long = (2 * numberOfSessions) * 24 * 60 * 60 * 1000L // approx!
					val randomTime = calendar.time.time - (0..twoDaysBetweenEachSession).random()

					calendar.timeInMillis = randomTime

					val startDate = calendar.time
					calendar.add(Calendar.HOUR_OF_DAY, (2..12).random())
					calendar.add(Calendar.MINUTE, (0..59).random())
					val endDate = calendar.time

					session.startDate = startDate
					session.endDate = endDate
					session.creationDate = startDate

					session.limit = Limit.values().random().ordinal
					session.game = games.random()

					session.result?.let { result ->
						val buyin = buyinList.random()
						result.buyin = buyinList.random()
						result.cashout = resultsList.random() + buyin
					}

				}

				realm.commitTransaction()

				val e = Date()
				val duration = (e.time - s.time) / 1000.0
				Timber.d("*** ended in ${duration} seconds")

				realm.close()

				callback?.invoke(true)

			} catch (e: Exception) {
				Timber.e(e)
				callback?.invoke(true)
			}
		}
	}

}