package com.rdiot.yx485.login;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.databinding.ActivitySplashBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.login.viewModel.LoginViewModel;
import com.rdiot.yx485.main.MainActivityTab;
import com.rdiot.yx485.util.IntentUtils;
import com.rdiot.yx485.util.LocalCache;

public class SplashActivity extends BaseActivity {
    private ActivitySplashBinding mBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivitySplashBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        LoginViewModel viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        viewModel.getErrorMessage().observe(this, this::showMessage);
        viewModel.getSplashPicture().observe(this, splashPicture -> {
            if (TextUtils.isEmpty(splashPicture.url)) {
                return;
            }

            showPicture(splashPicture.url);
        });
        viewModel.loadSplashPicture();

        // 使用 Handler 延迟跳转
        new Handler().postDelayed(() -> {
            boolean valid = LocalCache.verifyLoginState();
            if (valid) {
                // 跳转到 首页
                MainActivityTab.newIntent(this, false);
                finish();
            } else {
                // 跳转到 登录页面
                IntentUtils.intentToLogin(this);
            }
        }, 3000);
    }

    private void showPicture(String url) {
        LogUtils.d(url);
        Glide.with(this)
                .load(Url.BASE_URL + url)
                .into(mBinding.ivPicture);
    }
}