package com.pixelized.biblib.ui.screen.launch

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pixelized.biblib.network.client.IBibLibClient
import com.pixelized.biblib.network.data.query.AuthLoginQuery
import com.pixelized.biblib.repository.credential.ICredentialRepository
import com.pixelized.biblib.repository.googleSignIn.IGoogleSingInRepository
import com.pixelized.biblib.ui.navigation.Screen
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LauncherViewModel @Inject constructor(
    private val credentialRepository: ICredentialRepository,
    private val googleSignIn: IGoogleSingInRepository,
    private val client: IBibLibClient,
) : ViewModel() {

    var isLoadingDone by mutableStateOf(false)
        private set

    var startDestination: Screen = Screen.Authentication
        private set

    init {
        viewModelScope.launch {
            // Try to Authenticate
            startDestination = if (autoLoginWithGoogle() || autologinWithCredential()) {
                Screen.Home
            } else {
                Screen.Authentication
            }
            // Update loading state.
            isLoadingDone = true
        }
    }

    //////////////////////////////////////
    // region: Authentication

    private suspend fun autoLoginWithGoogle(): Boolean {
        val googleToken = googleSignIn.lastGoogleToken
        return if (googleToken != null) {
            try {
                client.service.loginWithGoogle(googleToken).let { response ->
                    if (response.token != null) {
                        client.token = response.token
                        true
                    } else {
                        false
                    }
                }
            } catch (e: Exception) {
                false
            }
        } else {
            false
        }
    }

    private suspend fun autologinWithCredential(): Boolean {
        val login = credentialRepository.login
        val password = credentialRepository.password
        return if (login != null && password != null && credentialRepository.bearer != null) {
            try {
                val query = AuthLoginQuery(login, password)
                client.service.login(query).let { response ->
                    if (response.token != null) {
                        client.token = response.token
                        credentialRepository.bearer = response.token
                        true
                    } else {
                        false
                    }
                }
            } catch (e: Exception) {
                false
            }
        } else {
            false
        }
    }

    // endregion
    //////////////////////////////////////
}