package com.pixelized.biblib.repository.user

import android.content.SharedPreferences
import androidx.core.content.edit
import com.pixelized.biblib.model.user.User
import com.pixelized.biblib.network.client.IBibLibClient
import com.pixelized.biblib.network.factory.UserFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class UserRepository(
    private val client: IBibLibClient,
    private val factory: UserFactory,
    private val preference: SharedPreferences,
) : IUserRepository {
    private var cache: User? = null

    @Throws
    override suspend fun user(forceUpdate: Boolean): User {
        val local = cache
        return when {
            local == null || forceUpdate -> fetchUserAndCache()
            else -> local
        }
    }

    override suspend fun lastUpdateDuration(): Long = withContext(Dispatchers.IO) {
        System.currentTimeMillis() - preference.getLong(USER_LAST_UPDATE, 0L)
    }

    @Throws
    suspend fun fetchUserAndCache(): User = withContext(Dispatchers.IO) {
        val response = client.service.user()
        return@withContext factory.fromUserResponseToUser(response).also {
            cache = it
            preference.edit { putLong(USER_LAST_UPDATE, System.currentTimeMillis()) }
        }
    }

    companion object {
        private const val USER_LAST_UPDATE = "USER_LAST_UPDATE"
    }
}