package com.house.wallpapers.myactivity;

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 android.widget.TextView;

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

import com.ad.toponlibrary.AdManager;
import com.google.android.material.color.DynamicColors;
import com.house.wallpapers.R;
import com.house.wallpapers.mytool.Comutils;

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

public class FirstActivity extends AppCompatActivity {
    private static final long SPLASH_TIME_OUT = 13000; // 总时长13秒
    private static final long PROGRESS_INTERVAL = 50; // 进度更新间隔（毫秒）
    private ProgressBar progressBar;
    private TextView tvProgress;
    private int currentProgress = 0;
    private CountDownTimer countDownTimer;

    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Comutils.initFull(this, false);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        setContentView(R.layout.activity_first);

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

        startProgressUpdate();
    }

    private void startProgressUpdate() {
                countDownTimer =  AdManager.showWelcomeAd(this, SPLASH_TIME_OUT, new Function1<Long, Unit>() {
                    @Override
                    public Unit invoke(Long aLong) {
                        int progressPercentage = (int) ((100 * aLong) / SPLASH_TIME_OUT);
                        int Percentage = 100 - progressPercentage;
                        progressBar.setProgress(Percentage);
                        tvProgress.setText(Percentage + "%");
                        return null;
                    }

                }, new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        Intent intent = new Intent(FirstActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();
                        return null;
                    }
                });
                countDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}