package com.datarecovery.master.dialog;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.view.animation.DecelerateInterpolator;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;

import com.datarecovery.master.dialog.BaseDialog;
import com.datarecovery.master.R;
import com.datarecovery.master.databinding.DialogScanProgressBinding;


@BaseDialog.FullScreen(height = false)
public class ScanProgressDialog extends BaseDialog<DialogScanProgressBinding> {


    private OnCancelListener onCancelListener;


    public ScanProgressDialog(@NonNull Context context, LiveData<Integer> totalDetectedCount) {
        super(context, R.style.Theme_Common_Dialog);
        setCancelable(false);
        binding.setCancelClick(v -> {
            if (onCancelListener != null)
                onCancelListener.onCancel();
            dismiss();
        });
        binding.setDetectedCount(totalDetectedCount);
    }

    public void setOnCancelListener(OnCancelListener onCancelListener) {
        this.onCancelListener = onCancelListener;
    }

    @Override
    public void show() {
        super.show();
        startProgress();
    }

    private void startProgress() {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 99);
        valueAnimator.setInterpolator(new DecelerateInterpolator());
        valueAnimator.addUpdateListener(animation -> {
            float value = (float) valueAnimator.getAnimatedValue();
            binding.setPercentageValue(value);
        });
        valueAnimator.setDuration(1000 * 60 * 3);
        valueAnimator.start();
    }

    public void detectedFinish() {
        dismiss();
//        float limit = 100 - binding.getPercentageValue();
//        ValueAnimator valueAnimator = ValueAnimator.ofFloat(binding.getPercentageValue(), 100);
//        valueAnimator.addUpdateListener(animation -> {
//            float value = (float) valueAnimator.getAnimatedValue();
//            binding.setPercentageValue(value);
//        });
//        valueAnimator.setDuration((int) limit * 100L);
//        valueAnimator.start();
//        valueAnimator.addListener(new AnimatorListenerAdapter() {
//            @Override
//            public void onAnimationEnd(Animator animation) {
//                dismiss();
//            }
//        });
    }


    public interface OnCancelListener {
        void onCancel();
    }
}
