package info.knacki.pass.ui.alertPrompt;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;

public class AlertPrompt {
    protected final AlertDialog.Builder fAlertBuilder;
    protected android.app.AlertDialog fDialog;
    protected View fView = null;
    protected final DismissListener fOnDismiss;
    protected final Context fContext;

    public interface OnClickListener {
        void onClick(DialogInterface dialogInterface, View view);
    }

    private class DismissListener implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener {
        private OnClickListener fListener;

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (fListener != null)
                fListener.onClick(dialog, fView);
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            if (fListener != null)
                fListener.onClick(dialog, fView);
        }

        void SetListener(OnClickListener listener) {
            fListener = listener;
        }
    }

    AlertPrompt(Context c) {
        fContext = c;
        fAlertBuilder = new AlertDialog.Builder(c);
        fOnDismiss = new DismissListener();
    }

    public AlertPrompt setView(View v) {
        fView = v;
        fAlertBuilder.setView(v);
        return this;
    }

    public View getView() {
        return fView;
    }

    public AlertPrompt setCancelable(boolean value) {
        fAlertBuilder.setCancelable(value);
        return this;
    }

    public AlertPrompt setPositiveButton(int textId, final OnClickListener listener) {
        fAlertBuilder.setPositiveButton(textId, (dialogInterface, i) -> listener.onClick(dialogInterface, fView));
        return this;
    }

    public AlertPrompt setNegativeButton(int textId, final OnClickListener listener) {
        fOnDismiss.SetListener(listener);
        fAlertBuilder.setNegativeButton(textId, fOnDismiss);
        fAlertBuilder.setOnCancelListener(fOnDismiss);
        return this;
    }

    public AlertPrompt setTitle(int textId) {
        fAlertBuilder.setTitle(textId);
        return this;
    }

    public AlertPrompt setTitle(String text) {
        fAlertBuilder.setTitle(text);
        return this;
    }

    protected void OnBeforeShow() {}

    public AlertPrompt show() {
        fDialog = fAlertBuilder.create();
        OnBeforeShow();
        fDialog.show();
        return this;
    }

    public void close() {
        if (fDialog != null) {
            fDialog.dismiss();
            fDialog = null;
        }
    }

    public AlertPrompt setPositiveButtonEnabled(boolean enabled) {
        fDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(enabled);
        return this;
    }
}
