package com.rjconsultores.ventaboletos.web.utilerias;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.UiException;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.impl.MessageboxDlg;

public class InputMessageBox extends Messagebox {
	
	private static Logger log = LogManager.getLogger(InputMessageBox.class);

    private static String oldTemplate = Messagebox.getTemplate();
	private static String _templ = "/component/inputMessageBox.zul";
	private static Textbox txtQuestion;

	public static final String showQuestion(String message, String title, int buttons) throws InterruptedException {
		setTemplate(_templ);
		String retorno = null;
		
		if (showInput(message, title, Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION, 0, null) == Messagebox.OK) {
			retorno = txtQuestion.getValue();
		}
        setTemplate(oldTemplate);
		return retorno;
	}
	
	public static final	int showInput(
			String message, 
			String title, 
			int buttons, 
			String icon, 
			int focus, 
			EventListener listener) throws InterruptedException {
		
		final Map<String, Object> params = new HashMap<>();
		params.put("message", message);
		params.put("title", title != null ? title: Executions.getCurrent().getDesktop().getWebApp().getAppName());
		params.put("icon", icon);
		params.put("buttons", (buttons & (OK|CANCEL|YES|NO|ABORT|RETRY|IGNORE)) != 0 ? buttons: OK);
		
		validateButtons(buttons, params);		

		final MessageboxDlg dlg = (MessageboxDlg)Executions.createComponents(_templ, null, params);
		dlg.setButtons(buttons);
		dlg.setEventListener(listener);
		txtQuestion = (Textbox)dlg.getFellowIfAny("txtQuestion");
		if (focus > 0) dlg.setFocus(focus);

		if (dlg.getDesktop().getWebApp().getConfiguration().isEventThreadEnabled()) {
			try {
				dlg.doModal();
			} catch (Exception ex) {
				if (ex instanceof InterruptedException)
					throw (InterruptedException)ex;
				try {
					dlg.detach();
				} catch (Exception ex2) {
					log.error("Failed to detach when recovering from an error " + ex2.toString());
				}
				throw UiException.Aide.wrap(ex);
			}
			return dlg.getResult();
		} else {
			dlg.doHighlighted();
			return OK;
		}
	}

	private static void validateButtons(int buttons, final Map<String, Object> params) {
		if ((buttons & OK) != 0)
			params.put("OK", OK);
		if ((buttons & CANCEL) != 0)
			params.put("CANCEL", CANCEL);
		if ((buttons & YES) != 0)
			params.put("YES", YES);
		if ((buttons & NO) != 0)
			params.put("NO", NO);
		if ((buttons & RETRY) != 0)
			params.put("RETRY", RETRY);
		if ((buttons & ABORT) != 0)
			params.put("ABORT", ABORT);
		if ((buttons & IGNORE) != 0)
			params.put("IGNORE", IGNORE);
	}

}
