package llc.arma.ble.data.repository

import llc.arma.ble.data.db.RotationsDao
import llc.arma.ble.data.model.RotationEntity
import llc.arma.ble.data.model.WheelEntity
import llc.arma.ble.domain.model.Rotation
import llc.arma.ble.domain.repository.RotationsRepository
import javax.inject.Inject

class RotationsRepositoryImpl @Inject constructor(
    private val dao: RotationsDao
) : RotationsRepository {

    override suspend fun saveRotations(rotations: List<Rotation>) {
        dao.deleteBySerialAndDateMoreThan(rotations.first().bleId, rotations.minOf { it.date } - 8)
        dao.save(
            rotations.map {
                RotationEntity(
                    bleId = it.bleId,
                    rotations = it.rotations,
                    date = it.date
                )
            }
        )
    }

    override suspend fun getRotationsBySerial(serial: String): List<Rotation> {
        return dao.getBySerialSortedByDate(serial).map {
            Rotation(
                bleId = it.bleId,
                rotations = it.rotations,
                date = it.date
            )
        }
    }

    override suspend fun deleteRotationsBySerial(serial: String) {
        dao.deleteBySerial(serial)
    }

    override suspend fun getWheelRadiusBySerial(serial: String): Long? {
        return dao.getWheelBySerial(serial)?.radius
    }

    override suspend fun setWheelRadius(serial: String, radius: Long) {
        dao.save(WheelEntity(serial, radius))
    }

}