package com.trust.ywx

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Process
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.trust.ywx.event.BundleUpdateEvent
import com.trust.ywx.utils.AppManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class WelcomeActivity : AppCompatActivity() {
    val handler = Handler(Looper.getMainLooper())
    val runnable = Runnable {
        if (MainApplication.isInit) {
            handler.removeCallbacks(runnableError)
            startActivity(Intent(this@WelcomeActivity, MainActivity::class.java))
            finish()
        }
    }
    val runnableError = Runnable {
        Toast.makeText(this, "初始化失败", Toast.LENGTH_SHORT).show()
        Process.killProcess(Process.myPid())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        AppManager.addActivity(this)
        handler.postDelayed(runnable, 3000)
        // 8秒没有完成初始化则显示初始化失败
        handler.postDelayed(runnableError, 8000)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: BundleUpdateEvent) {
        handler.removeCallbacks(runnable)
        handler.removeCallbacks(runnableError)
        startActivity(Intent(this@WelcomeActivity, MainActivity::class.java))
        finish()
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this);
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this);
    }

    override fun onDestroy() {
        super.onDestroy()
        AppManager.removeActivity(this)
    }
}
