package net.pokeranalytics.android.model.filter

import io.realm.RealmObject
import io.realm.RealmQuery
import net.pokeranalytics.android.model.filter.interfaces.Filterable
import java.util.*

enum class DateFilterable : Filterable {
    STARTED_FROM_DATE,
    STARTED_TO_DATE,
    ENDED_FROM_DATE,
    ENDED_TO_DATE,
    DAY_OF_WEEK,
    MONTH,
    YEAR,
    WEEK_DAY,
    WEEK_END,
    ;

    private enum class Field(var fieldName:String) {
        START_DATE("startDate"),
        END_DATE("endDate"),
        DAY("dayOfWeek"),
        MONTH("month"),
        YEAR("year"),
    }

    override var valueMap : Map<String, Any?>? = null

    override val filterValuesExceptedKeys : Array<String>?
        get() {
            return when (this) {
                STARTED_FROM_DATE, STARTED_TO_DATE, ENDED_FROM_DATE, ENDED_TO_DATE -> arrayOf("date")
                DAY_OF_WEEK -> arrayOf("dayOfWeek")
                MONTH -> arrayOf("month")
                YEAR -> arrayOf("year")
                else -> null
            }
        }

    override fun filter(realmQuery: RealmQuery<out RealmObject>): RealmQuery<out RealmObject> {
        return when (this) {
            STARTED_FROM_DATE -> {
                val date : Date by filterValues
                realmQuery.greaterThanOrEqualTo(Field.START_DATE.fieldName, date)
            }
            STARTED_TO_DATE -> {
                val date : Date by filterValues
                realmQuery.lessThanOrEqualTo(Field.START_DATE.fieldName, date)
            }
            ENDED_FROM_DATE -> {
                val date : Date by filterValues
                realmQuery.greaterThanOrEqualTo(Field.END_DATE.fieldName, date)
            }
            ENDED_TO_DATE -> {
                val date : Date by filterValues
                realmQuery.lessThanOrEqualTo(Field.END_DATE.fieldName, date)
            }
            DAY_OF_WEEK -> {
                val dayOfWeek : Int by filterValues
                realmQuery.equalTo(Field.DAY.fieldName, dayOfWeek)
            }
            MONTH -> {
                val month: Int by filterValues
                realmQuery.equalTo(Field.MONTH.fieldName, month)
            }
            YEAR -> {
                val year: Int by filterValues
                realmQuery.equalTo(Field.YEAR.fieldName, year)
            }
            WEEK_END -> {
                realmQuery.`in`(Field.DAY.fieldName, arrayOf(Calendar.SATURDAY,Calendar.SUNDAY))
            }
            WEEK_DAY -> WEEK_END.filter(realmQuery.not())
        }
    }
}