Newer
Older
MonCalc / app / src / main / kotlin / jackall / moncalc / db / MonstDataRealmHelper.kt
package jackall.moncalc.db

import io.realm.Realm
import io.realm.RealmModel
import io.realm.RealmObject
import io.realm.RealmResults
import jackall.moncalc.vo.Fruit
import jackall.moncalc.vo.Grade
import jackall.moncalc.vo.Temple

/**
 * Created by matsumoto_k on 2017/11/03.
 */
/**
 * fruit, temple, gradeのデータを管理するクラス
 */
class MonstDataRealmHelper {
    val templeRealmHelper = TempleRealmHelper()
    val fruitRealmHelper = FruitRealmHelper()
    val gradeRealmHelper = GradeRealmHelper()
    val realm by lazy { Realm.getInstance(RealmConfig().config) }

    fun update(realmObject: List<RealmObject>) {
        realm.executeTransaction {
            realm.copyToRealmOrUpdate(realmObject)
        }
    }

    fun <T : RealmModel> findAll(realmModel: Class<T>): RealmResults<T> {
        return realm.where(realmModel).findAll()
    }

    fun <T : RealmModel> findNames(realmModel: Class<T>): List<String> {
        val results = ArrayList<String>()
        when (realmModel) {
            Temple::class.java -> {
                realm.where(Temple::class.java).findAll().forEach {
                    results.add(it.name)
                }
            }
            Fruit::class.java -> {
                realm.where(Fruit::class.java).findAll().forEach {
                    results.add(it.name)
                }
            }
            Grade::class.java -> {
                realm.where(Grade::class.java).findAll().forEach {
                    results.add(it.name)
                }
            }
        }
        return results
    }

    fun <T : RealmModel> findIdByRank(realmModel: Class<T>, rank: Int): Int {
        when (realmModel) {
            Temple::class.java -> {
                return realm.where(realmModel).equalTo("rank", rank).findFirst().id
            }
            Fruit::class.java -> {
                return realm.where(realmModel).equalTo("rank", rank).findFirst().id
            }
            Grade::class.java -> {
                return realm.where(realmModel).equalTo("rank", rank).findFirst().id
            }
        }
        return -1
    }

    fun <T : RealmModel> findNameById(realmModel: Class<T>, id: Int): String {
        when (realmModel) {
            Temple::class.java -> {
                return realm.where(realmModel).equalTo("id", id).findFirst().name
            }
            Fruit::class.java -> {
                return realm.where(realmModel).equalTo("id", id).findFirst().name
            }
            Grade::class.java -> {
                return realm.where(realmModel).equalTo("id", id).findFirst().name
            }
        }
        return "unknown"
    }

    fun close() {
        templeRealmHelper.close()
        fruitRealmHelper.close()
        gradeRealmHelper.close()
    }
}