package com.prank.funnypranksounds.ui.activity;

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

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


public class SplashActivity extends AppCompatActivity {

    private ActivitySplashBinding binding;
    private static final long TOTAL_TIME = 11000;
    private CountDownTimer countDownTimer;

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

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

        EdgeToEdge.enable(this);
        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;
        });

        AdManager.loadAllAd();

        Glide.with(this)
                .load(R.mipmap.ic_launcher)
                .transform(new RoundedCorners(16))
                .into(binding.image);

        AdManager.setAlreadyShow();

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

        countDownTimer.start();
    }

    private void startMain() {
        binding.progress.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;
    }
}
