package net.pokeranalytics.android.model.utils

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


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

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

    private fun createDefaultTournamentFeatures(realm: Realm) {
        context.resources.getStringArray(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) {

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

        // Bankroll
        val bankroll = Bankroll()
        bankroll.name = context.resources.getString(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(R.array.seed_games)
        val gamesShortName = context.resources.getStringArray(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)
        }
    }

    private fun createDefaultTransactionTypes(realm: Realm) {
        TransactionType.Value.values().forEachIndexed { index, value ->
            val type = TransactionType()
            type.name = value.localizedTitle(context)
            type.additive = value.additive
            type.kind = index
            type.lock = true
            realm.insertOrUpdate(type)
        }
    }

}