package dev.inmo.postssystem.client.ui

import dev.inmo.postssystem.client.settings.auth.AuthSettings
import dev.inmo.postssystem.features.auth.client.ui.*
import dev.inmo.postssystem.features.auth.common.AuthCreds
import dev.inmo.postssystem.features.common.common.AbstractUIModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class DefaultAuthUIModel(
    private val scope: CoroutineScope,
    private val authSettings: AuthSettings
) : AbstractUIModel<AuthUIState>(LoadingAuthUIState), AuthUIModel {
    init {
        scope.launch {
            _currentState.value = LoadingAuthUIState
            authSettings.loadingJob.join()
            if (authSettings.authorizedDIModule.value == null) {
                _currentState.value = DefaultInitAuthUIState
            } else {
                _currentState.value = AuthorizedAuthUIState
            }
        }
    }

    override suspend fun initAuth(serverUrl: String, creds: AuthCreds) {
        _currentState.value = LoadingAuthUIState
        val authError = authSettings.auth(serverUrl, creds)
        if (authError == null) {
            _currentState.value = AuthorizedAuthUIState
        } else {
            _currentState.value = InitAuthUIState(authError)
        }
    }

}
