package com.lh.wallpaper2;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.ProgressBar;

import androidx.appcompat.app.AppCompatActivity;

import com.lh.wallpaper2.topon.AdManager;

public class InitialActivity extends AppCompatActivity {
    private ProgressBar progressBar;
    private CountDownTimer countDownTimer;

    private static final long totalTime = 11000; // 倒计时总时间
    private static final String TAG = "InitialActivity"; // 日志标签

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_initial);

        // 日志输出：进入 onCreate 方法
        Log.d(TAG, "onCreate: InitialActivity started");

        // 加载广告
        AdManager.loadAllAd();
        Log.d(TAG, "onCreate: Ads loaded");

        progressBar = findViewById(R.id.progressBar);

        // 重置进度条到初始状态
        progressBar.setProgress(0);

        AdManager.setAlreadyShow();

        // 每次进入活动时，重新创建并启动倒计时
        countDownTimer = AdManager.showWelcomeAd(
                InitialActivity.this,
                totalTime,
                millisUntilFinished -> {
                    int percentage = (int) (100 - (float) millisUntilFinished / totalTime * 100);
                    progressBar.setProgress(percentage);

                    // 日志输出：倒计时进度
                    Log.d(TAG, "onCreate: Progress updated to " + percentage + "%");
                },
                this::startMain // 倒计时结束或广告展示结束时，跳转主界面
        );

        // 日志输出：倒计时开始
        Log.d(TAG, "onCreate: Countdown timer started");
        countDownTimer.start();
    }

    // 跳转到主界面的方法
    private void startMain() {
        // 确保进度条更新至满值
        progressBar.setProgress(100);

        // 日志输出：倒计时结束，准备跳转到主界面
        Log.d(TAG, "startMain: Countdown finished, starting MainActivity");

        // 跳转到主界面
        Intent intent = new Intent(InitialActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 日志输出：进入 onDestroy 方法
        Log.d(TAG, "onDestroy: InitialActivity is being destroyed");

        // 在页面销毁时，清理倒计时资源
        if (countDownTimer != null) {
            countDownTimer.cancel();
            Log.d(TAG, "onDestroy: Countdown timer cancelled");
        }
    }
}
