package net.pokeranalytics.android.model.utils

import android.content.Context
import io.realm.Realm
import io.realm.kotlin.where
import net.pokeranalytics.android.model.realm.Bankroll
import net.pokeranalytics.android.model.realm.Currency
import net.pokeranalytics.android.model.realm.TournamentFeature
import java.util.*
import net.pokeranalytics.android.model.realm.Game
import net.pokeranalytics.android.util.UserDefaults


class Seed(var context:Context) : Realm.Transaction {

    override fun execute(realm: Realm) {
        this.createDefaultGames(realm)
        this.createDefaultTournamentFeatures(realm)
        this.createDefaultCurrencyAndBankroll(realm)
    }

    private fun createDefaultTournamentFeatures(realm: Realm) {
        context.resources.getStringArray(net.pokeranalytics.android.R.array.seed_tournament_features).forEach {
            val tournamentFeature = TournamentFeature()
            tournamentFeature.id = UUID.randomUUID().toString()
            tournamentFeature.name = it
            realm.insertOrUpdate(tournamentFeature)
        }
    }

    private fun createDefaultCurrencyAndBankroll(realm: Realm) {

        // Currency
        val localeCurrency = UserDefaults.getLocaleCurrency()
        val defaultCurrency = Currency()
        defaultCurrency.code = localeCurrency.currencyCode
        realm.insertOrUpdate(defaultCurrency)

        // Bankroll
        val bankroll = Bankroll()
        bankroll.name = context.resources.getString(net.pokeranalytics.android.R.string.live)
        bankroll.live = true
        bankroll.currency = realm.where<Currency>().equalTo("code", localeCurrency.currencyCode).findFirst()
        realm.insertOrUpdate(bankroll)
    }

    private fun createDefaultGames(realm: Realm) {
        val gamesName = context.resources.getStringArray(net.pokeranalytics.android.R.array.seed_games)
        val gamesShortName = context.resources.getStringArray(net.pokeranalytics.android.R.array.seed_games_short_name)
        for ((index, name) in gamesName.withIndex()) {
            val game = Game()
            game.id = UUID.randomUUID().toString()
            game.name = name
            game.shortName = gamesShortName[index]
            realm.insertOrUpdate(game)
        }
    }
}