Newer
Older
OverlayMultiCounter / app / src / main / kotlin / jackall / overlaymulticounter / db / CounterRealmHelper.kt
MatsumotoKeiju on 9 Nov 2017 1 KB [add] Edit counter title
package jackall.overlaymulticounter.db

import io.realm.RealmResults
import jackall.overlaymulticounter.vo.Counter

/**
 * Created by matsumoto_k on 2017/11/08.
 */
class CounterRealmHelper : BaseRealmHelper<Counter>() {
    override fun insert(realmObject: Counter) {
        realm.executeTransaction {
            realm.copyToRealm(realmObject)
        }
    }

    override fun update(realmObject: Counter) {
        realm.executeTransaction {
            realm.copyToRealmOrUpdate(realmObject)
        }
    }

    fun plus(id: Int) {
        realm.executeTransaction {
            realm.where(Counter::class.java).equalTo("id", id).findFirst().apply {
                count++
            }
        }
    }

    fun minus(id: Int) {
        realm.executeTransaction {
            realm.where(Counter::class.java).equalTo("id", id).findFirst().apply {
                if (count > 0)
                    count--
            }
        }
    }

    fun reset(id: Int) {
        realm.executeTransaction {
            realm.where(Counter::class.java).equalTo("id", id).findFirst().apply {
                count = 0
            }
        }
    }

    fun updateTitle(id: Int, title: String) {
        realm.executeTransaction {
            val counter = realm.where(Counter::class.java).equalTo("id", id).findFirst()
            counter.title = title
        }
    }

    fun resetAll() {
        realm.executeTransaction {
            findAll().forEach {
                it.count = 0
            }
        }
    }

    fun removeLast() {
        realm.executeTransaction {
            findAll().apply {
                if (count() > 0)
                    last().deleteFromRealm()
            }
        }
    }

    override fun findAll(): RealmResults<Counter> {
        return realm.where(Counter::class.java).findAll()
    }

    fun getNextId(): Int {
        val results = realm.where(Counter::class.java).findAll()
        return results.count()
    }
}