package com.bbitcn.silk.base;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.databinding.ViewDataBinding;

import com.bbitcn.silk.R;
import com.bbitcn.silk.ui.dialog.TipsDialog;
import com.bbitcn.silk.utils.log.MyLog;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import es.dmoral.toasty.Toasty;

/**
 * @Description 弹窗基类
 * @Author DuanKaiji
 * @CreateTime 2024年02月29日 14:49
 */
public abstract class BaseDialog<Binding extends ViewDataBinding> extends Dialog {
    protected Binding binding;
    protected Context mContext;

    public BaseDialog(@NonNull Context context) {
        this(context, false);
    }

    /**
     * 构造函数
     *
     * @param context   上下文
     * @param needInput 是否需要输入，即软键盘弹出
     */
    public BaseDialog(@NonNull Context context, boolean needInput) {
        super(context, R.style.MyDialogTheme);
        mContext = context;
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Class<Binding> bindingClass = (Class<Binding>) ((ParameterizedType) type).getActualTypeArguments()[0];
            try {
                Method inflateMethod = bindingClass.getMethod("inflate", LayoutInflater.class);
                binding = (Binding) inflateMethod.invoke(null, getLayoutInflater());
                setContentView(binding.getRoot());
                findViewById(R.id.iv_dialog_close).setOnClickListener(view -> dismiss());
                getWindow().setGravity(Gravity.CENTER);
                if (!needInput) {
                    getWindow().setAttributes(getAttributes(this));
                }
            } catch (Exception e) {
                MyLog.appError("BaseDialog初始化失败:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public interface CustomString {
        /**
         * @param selString 选中的项
         */
        void listener(String selString);
    }
    /**
     * 获得弹窗属性设置
     * 全屏弹窗，但无法使用输入法
     */
    public static WindowManager.LayoutParams getAttributes(Dialog dialog) {
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.gravity = Gravity.CENTER;
        layoutParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
        layoutParams.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
        return layoutParams;
    }

}
