package com.epson.mobilephone.common.license;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;

import epson.print.R;


/**
 * 自定义对话框
 */
public class SimpleMessageDialogFragment extends DialogFragment {

    private static final String PARAM_DIALOG_ID = "dialog_id";
    private static final String PARAM_MESSAGE_STRING = "message_string";
    private DialogCallback mDialogCallback;
    private int mDialogId;
    private String mMessageString;

    interface DialogCallback {
        void onButtonClicked(int i);
    }

    /**
     * 实例化一个单确认按钮的对话框
     *
     * @param str 显示字符串
     * @param i   对话框id
     * @return
     */
    @NonNull
    public static SimpleMessageDialogFragment newInstance(String str, int i) {
        SimpleMessageDialogFragment simpleMessageDialogFragment = new SimpleMessageDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(PARAM_DIALOG_ID, i);
        bundle.putString(PARAM_MESSAGE_STRING, str);
        simpleMessageDialogFragment.setArguments(bundle);
        return simpleMessageDialogFragment;
    }

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        Bundle arguments = getArguments();
        mDialogId = arguments.getInt(PARAM_DIALOG_ID);
        mMessageString = arguments.getString(PARAM_MESSAGE_STRING);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle bundle) {
        super.onCreateDialog(bundle);
        AlertDialog create = new AlertDialog.Builder(getActivity()).setMessage(mMessageString).setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                onOkClicked();
            }
        }).create();
        setCancelable(false);
        return create;
    }

    /**
     * 对话框点击事件
     */
    private void onOkClicked() {
        mDialogCallback.onButtonClicked(mDialogId);
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mDialogCallback = (DialogCallback) activity;
        } catch (ClassCastException unused) {
            throw new ClassCastException(activity.toString() + " must implement DialogCallback");
        }
    }

    public void onDetach() {
        super.onDetach();
        mDialogCallback = null;
    }
}
