package net.pokeranalytics.android.model.filter

import io.realm.RealmQuery

fun List<Query>.mapFirstCondition() : List<QueryCondition> {
	return this.map { it.conditions.first() }
}

class Query {

	constructor(vararg elements: QueryCondition) {
		if (elements.size > 0) {
			this.add(elements.asList())
		}
	}

	private val _conditions: MutableList<QueryCondition> = mutableListOf()
	val conditions: List<QueryCondition>
		get() {
			return this._conditions
		}

	fun add(vararg elements: QueryCondition) {
		if (elements.size > 0) {
			this.add(elements.asList())
		}
	}

	fun add(queryCondition: QueryCondition) {
		this._conditions.add(queryCondition)
	}

	fun remove(queryCondition: QueryCondition) {
		this._conditions.remove(queryCondition)
	}

	fun add(queryConditions: List<QueryCondition>) {
		this._conditions.addAll(queryConditions)
	}

	val name: String
		get() {
			return this._conditions.joinToString(" : ") { it.getDisplayName() }
		}

	inline fun <reified T : Filterable> queryWith(query: RealmQuery<T>): RealmQuery<T> {
		var realmQuery = query
		this.conditions.forEach {
			realmQuery = it.queryWith(realmQuery)
		}
		return realmQuery
	}

	fun merge(query: Query) : Query {
		this.add(query.conditions)
		return this
	}

}