package com.example.makcar

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull

class LoadingPage : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_loading_page)

        // 只 collect 一次 true → 跳主屏
        (application as MyApplication).ready
            .filter { it }                 // 只要 true
            .onEach {
                startActivity(Intent(this, MainActivity::class.java))
                finish()                  // 闪屏必须死
            }
            .launchIn(lifecycleScope)     // 生命周期内自动取消


        // 5 秒超时兜底（连接失败 / 没插飞机）
        lifecycleScope.launch {
            val connected = withTimeoutOrNull(5_000) {
                (application as MyApplication).ready.filter { it }.first()
            }
            if (connected == null) {          // 超时
                Toast.makeText(
                    this@LoadingPage,
                    "连接超时，请检查遥控器/飞机",
                    Toast.LENGTH_LONG
                ).show()
                finish()      //超时关闭
            }
        }

    }
}