package net.pokeranalytics.android.model.migrations

import android.content.Context
import io.realm.Realm
import net.pokeranalytics.android.model.filter.Query
import net.pokeranalytics.android.model.filter.QueryCondition
import net.pokeranalytics.android.model.realm.*
import net.pokeranalytics.android.util.Preferences

class Patcher {

	companion object {

		fun patchAll(context: Context) {

			Preferences.executeOnce(Preferences.Keys.PATCH_BREAK, context) {
				patchBreaks()
			}
			Preferences.executeOnce(Preferences.Keys.PATCH_TRANSACTION_TYPES_NAMES, context) {
				patchDefaultTransactionTypes(context)
			}

		}

		private fun patchBreaks() {

			val realm = Realm.getDefaultInstance()
			val sets = realm.where(SessionSet::class.java).findAll()
			val sessions = Filter.queryOn<Session>(realm, Query(QueryCondition.IsCash))
            val results = realm.where(Result::class.java).findAll()

			realm.executeTransaction {
				sets.forEach {
					it.computeStats()
				}
                sessions.forEach {
                    it.formatBlinds()
                }
                results.forEach {
                    it.computeNumberOfRebuy()
                }
			}

			realm.close()

		}

		private fun patchDefaultTransactionTypes(context: Context) {
			val realm = Realm.getDefaultInstance()
			realm.executeTransaction {
				val tts = realm.where(TransactionType::class.java).findAll()
				tts.forEach { tt ->
					tt.kind?.let { kind ->
						val value = TransactionType.Value.values()[kind]
						tt.name = value.localizedTitle(context)
					}
				}
			}
			realm.close()
		}

	}

}