package net.pokeranalytics.android.model.migrations

import io.realm.DynamicRealm
import io.realm.RealmMigration
import timber.log.Timber


class PokerAnalyticsMigration : RealmMigration {

	override fun migrate(realm: DynamicRealm, oldVersion: Long, newVersion: Long) {

		// DynamicRealm exposes an editable schema
		val schema = realm.schema

		var currentVersion = oldVersion.toInt()
		Timber.d("*** migrate from $oldVersion to $newVersion")

		// Migrate to version 1
		if (currentVersion == 0) {
			Timber.d("*** Running migration 1")

			schema.get("Filter")?.let {
				it.addField("entityType", Int::class.java).setNullable("entityType", true)
			}
			schema.get("FilterElement")?.let {
				it.setNullable("filterName", true)
				it.setNullable("sectionName", true)
			}
			schema.get("FilterElementBlind")?.let {
				it.renameField("code", "currencyCode")
			}
			currentVersion++
		}

		// Migrate to version 2
		if (currentVersion == 1) {
			Timber.d("*** Running migration ${currentVersion + 1}")
			schema.rename("FilterElement", "FilterCondition")
			schema.get("Filter")?.let {
				it.renameField("filterElements", "filterConditions")
			}
			schema.get("SessionSet")?.let {
				it.addField("id", String::class.java).setRequired("id", true)
				it.addPrimaryKey("id")
			}
			currentVersion++
		}

		// Migrate to version 2
		if (currentVersion == 2) {
			Timber.d("*** Running migration ${currentVersion + 1}")
			schema.rename("Report", "ReportSetup")

            schema.get("Session")?.let {
                it.addField("blinds", String::class.java)
            }

            schema.get("FilterCondition")?.let {
                it.addRealmListField("booleanValues", Boolean::class.java).setNullable("booleanValues", true)
            }

            schema.get("FilterCondition")?.let {
                it.removeField("blindValues")
            }

            currentVersion++
		}

	}

	override fun equals(other: Any?): Boolean {
		return other is RealmMigration
	}

	override fun hashCode(): Int {
		return RealmMigration::javaClass.hashCode()
	}
}