package com.ardraw.ardrawinggallery.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.ardraw.ardrawinggallery.R;
import com.ardraw.ardrawinggallery.databinding.ActivityLaunchBinding;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;

public class LaunchActivity extends AppCompatActivity {
    private ActivityLaunchBinding binding;
    private static final long TOTAL_TIME = 3000;
    private CountDownTimer countDownTimer;

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

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

        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;
        });

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

        countDownTimer = new CountDownTimer(TOTAL_TIME, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                int percentage = (int) (100 - (float) millisUntilFinished / TOTAL_TIME * 100);
                binding.progressBar.setProgress(percentage);
            }

            @Override
            public void onFinish() {
                startMain();
            }
        };

        countDownTimer.start();
    }

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

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

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