package llc.arma.ble.domain.usecase

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onEach
import llc.arma.ble.domain.Result
import llc.arma.ble.domain.common.BleException
import llc.arma.ble.domain.common.ProgressState
import llc.arma.ble.domain.model.Ble
import llc.arma.ble.domain.model.Rotation
import llc.arma.ble.domain.repository.BleRepository
import llc.arma.ble.domain.repository.RotationsRepository
import java.util.concurrent.TimeUnit
import javax.inject.Inject

class GetAccelerometerHistoryBySerial @Inject constructor(
    private val bleRepository: BleRepository,
    private val rotationsRepository: RotationsRepository
) {

    suspend operator fun invoke(serial: String): Flow<Result<ProgressState<List<Ble.Accelerometer.HistoryPoint>>, BleException>> {

        return bleRepository.getAccelerometerHistoryBySerial(serial).onEach {
            it.onSuccess { progress ->
                if(progress is ProgressState.Finished){
                    val rotations = progress.data.mapNotNull { point ->
                        if(point is Ble.Accelerometer.HistoryPoint.Rotation){
                            Rotation(
                                bleId = serial,
                                date = TimeUnit.SECONDS.toMillis(TimeUnit.MILLISECONDS.toSeconds(point.date)),
                                rotations = point.value
                            )
                        }else{
                            null
                        }

                    }
                    if(rotations.isNotEmpty()){

                        rotationsRepository.saveRotations(rotations)

                    }
                }
            }
        }

    }

}