package com.ar.imagetracear.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

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.ar.imagetracear.R;
import com.ar.imagetracear.databinding.ActivitySplashBinding;
import com.ar.imagetracear.topon.AdManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

public class SplashActivity extends AppCompatActivity {
    private ActivitySplashBinding binding;
    private static final long totalTime = 11000;
    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EdgeToEdge.enable(this);

        binding = ActivitySplashBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        View mainLayout = findViewById(R.id.main);
        ViewCompat.setOnApplyWindowInsetsListener(mainLayout, (view, windowInsets) -> {
            Insets bars = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars());
            view.setPadding(bars.left, bars.top, bars.right, bars.bottom);
            return windowInsets;
        });

        AdManager.loadAllAd();
        AdManager.setAlreadyShow();

        Glide.with(this)
                .load(R.mipmap.ic_launcher)
                .transform(new CenterCrop(),new RoundedCorners(32))
                .placeholder(R.mipmap.placeholder)
                .error(R.mipmap.placeholder)
                .into(binding.splashImage);

        countDownTimer = AdManager.showWelcomeAd(this, totalTime, millisUntilFinished -> {
                    int percentage = (int) (100 - (float) millisUntilFinished / totalTime * 100);
                    binding.progressBar.setProgress(percentage);
                },
                this::startToJump
        );

        countDownTimer.start();
    }

    private void startToJump() {
        binding.progressBar.setProgress(100);

        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        binding = null;
    }
}