package hh.dejsem.fm;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.widget.EditText;

import hh.dejsem.K;
import hh.lib.D;

/**
 * "edit text entry" dialog
 */
public class DialogFragmentEntry extends DialogFragment implements DialogInterface.OnClickListener {
	static final String TAG = "enter text dialog";

	D d;
	FragmentActivity a;
	EditText editText;
	String title, message, text;
	int action;
	boolean localFS;
	AlertDialog dialog = null;

	/**
	 *
	 * @param savedInstanceState
	 * @return
	 */
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		d.l(3, String.format("onCreateDialog, action=" + action));
		setRetainInstance(true);
		if(dialog == null) {
			/*LayoutInflater inflater = getActivity().getLayoutInflater();
			editText = (EditText)inflater.inflate(R.layout.text_dialog, null);*/
			editText = new EditText(a);
			editText.setEms(10);
			editText.setText(text);
			dialog = new AlertDialog.Builder(getActivity())
					.setCancelable(true)
					.setView(editText)
					.setTitle(title)
					.setMessage(message)
					.setPositiveButton("OK", this)
					.setNegativeButton("Cancel", null)
					.create();
		}
		return dialog;
	}

	/**
	 *
	 * @param dialog
	 * @param id
	 */
	@Override
	public void onClick(DialogInterface dialog, int id) {
		final String result = editText.getText().subSequence(0, editText.length()).toString();
		if(d.ll(4)) d.l(String.format("OK from edit text, text=%s, edited text=%s", text, result));
		final FM fm = localFS ? FragFM.localDirPanel.fm : FragFM.remoteDirPanel.fm;
		try {
			if(action == K.FM_ACTION_RENAME)
				fm.renameSelected(result);
			else if(action == K.FM_ACTION_CREATE) fm.doCreateDir(result);
		} catch(Exception e) { d.abendMsg(e); }
	}

	/**
	 *
	 */
	@Override
	public void onDestroyView() {
		d.l(3, "onDestroyView");
		Dialog dialog = getDialog();
		// Work around bug: http://code.google.com/p/android/issues/detail?id=17423
		if ((dialog != null) && getRetainInstance()) dialog.setDismissMessage(null);
		super.onDestroyView();
	}

	/**
	 * příprava DialogFragmentu pro vstup textu
	 * BACHA, kompletace samotného Fragmentu se spouští až při show(), takže getFmgr() je třeba brát z rodiče
	 *
	 * @param parentPanel
	 * @param title
	 * @param message
	 * @param text
	 * @param action
	 */
	void enterText(PanelDirView parentPanel, String title, String message, String text, int action) {
		this.d = parentPanel.d.klon(this);
		a = parentPanel.d.getAct();
		localFS = PanelLocalDir.class.isInstance(parentPanel);
		this.title = title;
		this.message = message;
		this.text = text;
		this.action = action;
		show(a.getSupportFragmentManager(), TAG);
	}

}
