package com.develop.common.dialog;

import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.activity.ComponentActivity;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.UiThread;

public class PlainDialogView {
    private final ComponentActivity activity;
    private final int layoutId;
    private View dialogRoot;
    private View dialogView;
    private boolean dialogShow;
    private boolean cancelable;
    private final OnBackPressedCallback onBackPressedCallback = new OnBackPressedCallback(false) {
        @Override
        public void handleOnBackPressed() {
            if (cancelable) {
                hideDialog();
            }
        }
    };

    public PlainDialogView(ComponentActivity activity, int layoutId) {
        this.activity = activity;
        this.layoutId = layoutId;
        activity.getOnBackPressedDispatcher().addCallback(onBackPressedCallback);
    }

    public void showDialog() {
        showDialog(false);
    }

    @UiThread
    public void showDialog(boolean cancelable) {
        this.dialogShow = true;
        this.cancelable = cancelable;
        if (dialogRoot == null) {
            dialogRoot = new FrameLayout(activity);
            dialogRoot.setClickable(true);
            dialogRoot.setBackgroundColor(Color.parseColor("#AA000000"));
            dialogRoot.setLayoutParams(new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            ));
        }
        if (dialogView == null) {
            dialogView = View.inflate(activity, layoutId, (ViewGroup) dialogRoot);
        }
        detachRootView();
        dialogRoot.setAlpha(0f);
        FrameLayout container = (FrameLayout) activity.getWindow().getDecorView();
        container.addView(dialogRoot, new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.MATCH_PARENT
        ));
        dialogRoot.animate().alpha(1f).setDuration(300).start();
        onBackPressedCallback.setEnabled(true);
    }

    @UiThread
    public void hideDialog() {
        onBackPressedCallback.setEnabled(false);
        if (dialogView == null) {
            return;
        }
        if (dialogRoot.getParent() == null || !dialogShow) {
            return;
        }
        dialogShow = false;
        dialogRoot.animate().alpha(0f).setDuration(200).withEndAction(this::detachRootView);
    }

    private void detachRootView() {
        ViewGroup parent = (ViewGroup) dialogRoot.getParent();
        if (parent != null) {
            parent.removeView(dialogRoot);
        }
    }
}
