package ru.yandex.qe.dispenser.domain.dao.bot.bigorder

import ru.yandex.qe.dispenser.domain.bot.BigOrder

class BigOrderDaoImpl: BigOrderDao {

    private val collection: MutableList<BigOrder> = mutableListOf()

    @Synchronized
    override fun getById(id: Long): BigOrder? {
        return collection.firstOrNull { v -> v.id == id }
    }

    @Synchronized
    override fun getByIds(ids: Collection<Long>): Set<BigOrder> {
        val idsSet = ids.toSet()
        return collection.filter { idsSet.contains(it.id) }.toSet()
    }

    @Synchronized
    override fun getPage(idFrom: Long?, limit: Long): List<BigOrder> {
        return if (idFrom == null) {
            collection.sortedBy { it.id }.filterNot { it.isDeleted }.take(limit.toInt())
        } else {
            collection.sortedBy { it.id }.filter { !it.isDeleted && it.id > idFrom }.take(limit.toInt())
        }
    }

    @Synchronized
    override fun getAll(): Set<BigOrder> {
        return collection.toSet()
    }

    @Synchronized
    override fun create(builder: BigOrder.Builder): BigOrder {
        val nextId = (collection.maxByOrNull { it.id }?.id ?: -1L) + 1L
        val result = builder.build(nextId)
        collection.add(result)
        return result
    }

    @Synchronized
    override fun update(update: BigOrder.Update): BigOrder {
        val updated = update.build()
        val indexOf = collection.indexOfFirst { it.id == updated.id }
        if (indexOf < 0) {
            throw IllegalArgumentException("No big order with id ${updated.id}")
        }
        collection.removeAt(indexOf)
        collection.add(updated)
        return updated
    }

    @Synchronized
    override fun clear(): Boolean {
        collection.clear()
        return true
    }

}
