package com.datarecovery.master.dialog;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;

import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.Constants;
import com.tencent.qgame.animplayer.AnimView;

import java.util.concurrent.TimeUnit;

import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.rxjava.utils.RxJavaUtil;

@BaseDialog.FullScreen
public class AdLoadingDialog extends BaseDialog {

    private static final int DismissWhat = 588;
    private Disposable dismissTimer;
    private long showTime;
    private final Handler handler;

    public AdLoadingDialog(@NonNull Context context, @LayoutRes int loadingLayoutRes, int loadingStyleRes) {
        super(context, loadingStyleRes);
        setCancelable(false);
        setContentView(loadingLayoutRes);
        handler = new Handler(Looper.getMainLooper(), msg -> {
            if (msg.what == DismissWhat) {
                dismiss();
                return true;
            }
            return false;
        });
    }

    @Override
    protected void onShow() {
        super.onShow();
        showTime = System.currentTimeMillis();
        dismissTimer = RxJavaUtil.timer(
                Constants.Dialog_VIDEO_LOADING_COUNTDOWN,
                TimeUnit.MILLISECONDS, this::dismiss
        );
        startLoadingAnim();
    }

    private void startLoadingAnim() {
        View loadingAnim = findViewById(R.id.ad_loading_anim);
        AnimView animView = loadingAnim instanceof AnimView ? ((AnimView) loadingAnim) : null;
        if (animView != null) {
            animView.setLoop(Integer.MAX_VALUE);
            animView.startPlay(getContext().getAssets(), "anim/loading.mp4");
        }
    }

    private void stopLoadingAnim() {
        View loadingAnim = findViewById(R.id.ad_loading_anim);
        AnimView animView = loadingAnim instanceof AnimView ? ((AnimView) loadingAnim) : null;
        if (animView != null) {
            animView.stopPlay();
        }
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
        if (dismissTimer != null) {
            dismissTimer.dispose();
        }
        stopLoadingAnim();
    }

    @Override
    public void dismiss() {
        long l = System.currentTimeMillis() - showTime;
        if (l < 1500) {
            handler.sendEmptyMessageDelayed(DismissWhat, 1500 - l);
            return;
        }
        super.dismiss();
    }

    public final void forceDismiss() {
        super.dismiss();
    }

    @Override
    public boolean useQueue() {
        return false;
    }
}