package com.wall.engine.wallpaper;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.widget.ProgressBar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.ad.tradpluslibrary.TPAdManager;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;

public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;

    private Handler handler;
    private long totalTime = 13000;
    private CountDownTimer countDownTimer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 初始化控件
        progressBar = findViewById(R.id.progressBar);
        handler = new Handler(Looper.getMainLooper());


        TPAdManager.INSTANCE.init(MainActivity.this, App.TAG, "AA8164DB9D6A35CF63E3DA2B6566D611", "D5E5214E665A8B7F389884D96E888B12", "D3F5AAA6CE3FB2559A14115FE435AE12", "A8EFAD3EA7A59AC823B44C0F53718E12", new Function0<Unit>() {
            @Override
            public Unit invoke() {
                return null;
            }
        });

          countDownTimer = TPAdManager.INSTANCE.showWelcomeAd(MainActivity.this, totalTime, new Function1<Long, Unit>() {
            @Override
            public Unit invoke(Long aLong) {
                int progressPercentage = (int) ((100 * aLong) / totalTime);
                int countdownPercentage = 100 - progressPercentage;
                progressBar.setProgress(countdownPercentage);
                return null;
            }
        }, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
                finish();  // 关闭启动页，避免返回键回到此页面
                return null;
            }
        });
        countDownTimer.start();


        // 适配系统状态栏（保留原有逻辑）
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    // 防止页面销毁时Handler内存泄漏
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }
}