parent
37913ced3f
commit
6910745e5b
@ -0,0 +1,71 @@ |
|||||||
|
package net.pokeranalytics.android.util |
||||||
|
|
||||||
|
import io.realm.Realm |
||||||
|
import io.realm.RealmModel |
||||||
|
import io.realm.RealmResults |
||||||
|
import io.realm.Sort |
||||||
|
import io.realm.kotlin.where |
||||||
|
import net.pokeranalytics.android.model.interfaces.CountableUsage |
||||||
|
import net.pokeranalytics.android.model.realm.Session |
||||||
|
import net.pokeranalytics.android.model.realm.TournamentFeature |
||||||
|
import net.pokeranalytics.android.model.realm.Transaction |
||||||
|
|
||||||
|
/** |
||||||
|
* Returns all entities of the [clazz] sorted with their default sorting |
||||||
|
*/ |
||||||
|
fun <T : RealmModel> Realm.sorted(clazz: Class<T>) : RealmResults<T> { |
||||||
|
|
||||||
|
if (clazz is CountableUsage) { |
||||||
|
this.updateUsageCount(clazz) |
||||||
|
} |
||||||
|
|
||||||
|
val sortField = when (clazz) { |
||||||
|
is CountableUsage -> "useCount" |
||||||
|
is Transaction -> "date" |
||||||
|
else -> "name" |
||||||
|
} |
||||||
|
val resultSort = when (clazz) { |
||||||
|
is CountableUsage -> Sort.DESCENDING |
||||||
|
is Transaction -> Sort.DESCENDING |
||||||
|
else -> Sort.ASCENDING |
||||||
|
} |
||||||
|
|
||||||
|
return this.where(clazz).findAll().sort(sortField, resultSort) |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Returns all entities of the [clazz] sorted with their default sorting |
||||||
|
*/ |
||||||
|
inline fun <reified C : RealmModel> Realm.sorted() : RealmResults<C> { |
||||||
|
return this.sorted(C::class.java) |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Updates the useCount variable of the CountableUsage entity |
||||||
|
*/ |
||||||
|
fun <T : RealmModel>Realm.updateUsageCount(clazz: Class<T>) { |
||||||
|
|
||||||
|
val results = this.where(clazz).findAll() |
||||||
|
this.executeTransaction { |
||||||
|
results.forEach { countableUsage -> |
||||||
|
|
||||||
|
val countable = (countableUsage as CountableUsage) |
||||||
|
when (clazz) { |
||||||
|
is TournamentFeature -> { |
||||||
|
countable.useCount = it.where<Session>().contains( |
||||||
|
"tournamentFeatures.id", |
||||||
|
countable.id |
||||||
|
).count().toInt() |
||||||
|
} |
||||||
|
else -> { |
||||||
|
countable.useCount = it.where<Session>().equalTo( |
||||||
|
"${clazz.simpleName.decapitalize()}.id", |
||||||
|
countable.id |
||||||
|
).count().toInt() |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
Loading…
Reference in new issue