package com.ys.bdtp.adm.mvvm.ui.screen.flash

import android.content.SharedPreferences
import android.net.ConnectivityManager
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.ys.bdtp.adm.app.Token
import com.ys.bdtp.adm.app.isNet
import com.ys.bdtp.adm.mvvm.ui.screen.main.Zygote
import com.ys.bdtp.adm.mvvm.vm.flash.FlashViewModel
import kotlinx.coroutines.delay
import org.kodein.di.compose.rememberInstance
import org.kodein.di.compose.rememberViewModel


@Composable
fun FlashScreen(block: (Zygote) -> Unit) {
    val vm by rememberViewModel<FlashViewModel>()
    val cm by rememberInstance<ConnectivityManager>()
    val zygote by rememberUpdatedState(block)
    val sp by rememberInstance<SharedPreferences>()
    LaunchedEffect(Unit) {
        delay(5000)
        val user = vm.getCurrentUser()
        val isNet = isNet(cm)

        when {
            user == null -> { // 未登录
                zygote(Zygote.Login)
            }
            !isNet -> { // 登录 && 未联网
                zygote(Zygote.Project)
            }
            else -> {  // 未登录 && 未联网
                val token = sp.getString(Token, "")
                if (token == "")
                    zygote(Zygote.Login)
                else
                    vm.getAccount(
                        success = {
                            zygote(Zygote.Project)
                        },
                        failure = {
                            zygote(Zygote.Login)
                        }
                    )
            }
        }
    }

    Column(
        modifier = Modifier.fillMaxSize().background(Color.White),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "Yushu", fontSize = 24.sp)
    }
}

@Preview
@Composable
fun PreviewFlashScreen() {
    FlashScreen(block = { })
}