package hh.dejsem.fm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.net.URI;
import java.net.URLConnection;
import java.util.ArrayList;

import hh.dejsem.FlatButton;
import hh.dejsem.K;
import hh.dejsem.Prefs;
import hh.dejsem.R;
import hh.dejsem.SendUriNG;
import hh.dejsem.hack.HackFS;
import hh.dejsem.hack.HackNotifListAct;
import hh.dejsem.hack.HackUDP;
import hh.dejsem.net.NetConn;
import hh.dejsem.net.PullFromPeer;
import hh.dejsem.net.PushToPeer;
import hh.dejsem.net.SrvCmd;
import hh.lib.D;
import hh.lib.NoticeDialogFragment;

/**
 * screen panel for operations on directory list view
 * <p>
 *     ● drží hlavně menu operací a metody, které je spouštějí
 * <p>
 *     ● vnořená třída DirListView drží subviews (záhlaví a ListView)
 * <p>
 *     ● panely se v okně zobrazují jeden (lokální FS) nebo dva (lokální a serverový FS)
 *     a dědí je třídy PanelServerDir, PanelServerMoveDest, PanelLocalDir, PanelLocalMoveDest, PanelPeerDir
 */
class PanelDirView {

	/**
	 * directory list to be displayed in screen panel
	 */
	static class DirListView {

		D d;
		PanelDirView panel;
		final int dirNameColor;
		final float dirNameSize;
		final ImageView up, menu;
		final HorizontalScrollView dirNameScroll;
		final LinearLayout dirNameView;
		final ListView dirListView;
		final int whichFS;
		String path;
		final View.OnClickListener goToClick = new View.OnClickListener() { public void onClick(View v) { panel.handleGoToDir(v); } };
		final View.OnClickListener upClick = new View.OnClickListener() { public void onClick(View v) { panel.handleDirUp(); } };
		final View.OnClickListener menuClick = new View.OnClickListener() { public void onClick(View v) { openContextMenu(); } };
		final AdapterView.OnItemClickListener itemClick = new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int pos, long id) { panel.handleClickedListEntry(pos); }
		};

		static RelativeLayout getLayout(Context c) { return (RelativeLayout) LayoutInflater.from(c).inflate(R.layout.dir_view_layout, null); }

		DirListView(PanelDirView panel, RelativeLayout dirViewContainer, String dirViewLabel, int whichFS) {
			this.d = panel.d.klon(this);
			this.panel = panel;
			this.whichFS = whichFS;

			up = (ImageView)dirViewContainer.findViewById(R.id.up);
			dirNameScroll = (HorizontalScrollView)dirViewContainer.findViewById(R.id.scroll);
			dirNameView = (LinearLayout)dirViewContainer.findViewById(R.id.dirname);
			dirNameColor = d.getContext().getResources().getColor(R.color.dir_name_color);
			dirNameSize = d.getContext().getResources().getDimension(R.dimen.dir_name_size);
			((TextView)dirViewContainer.findViewById(R.id.site)).setText(dirViewLabel);
			menu = (ImageView)dirViewContainer.findViewById(R.id.menu);
			dirListView = (ListView)dirViewContainer.findViewById(R.id.dir_list_view);
		}

		void setUpDirView() {
			up.setOnClickListener(upClick);
			d.getFragment().registerForContextMenu(dirListView);
			dirListView.setTag(whichFS);  // local or remote FM
			menu.setOnClickListener(menuClick);
			d.getFragment().registerForContextMenu(menu);
			menu.setTag(whichFS);         // local or remote FM
			dirListView.setOnItemClickListener(itemClick);
			updateDirView();
		}

		void updateDirView() {
			assembleDirname();
			dirListView.setAdapter(panel.fm.getListAdapter());
			dirListView.setSelection(panel.fm.cwdFl.listPos);
		}

		void assembleDirname() {
			final String dirname = panel.fm.getCwdName();
			if(d.ll(5)) d.l(String.format("dirname=%s", dirname));
			dirNameView.removeAllViews();
			if(dirname.length() > 0) {
				path = "";
				setNameButton("/");
				for(String name : dirname.split("/")) setNameButton(name);
				dirNameScroll.post(new Runnable() { public void run() { dirNameScroll.fullScroll(View.FOCUS_RIGHT); } });
			}
		}

		void setNameButton(String name) {
			if(name.equals("")) return;
			if(path.equals("/") || name.equals("/")) path += name;
			else path += "/" + name;
			FlatButton dirNameElement = new FlatButton(d.getContext());
			dirNameElement.setTag(path);
			dirNameElement.setColor(dirNameColor);
			dirNameElement.setSize(dirNameSize);
			dirNameElement.setText(name.equals("/") ? " / " : name);
			dirNameElement.setOnClickListener(goToClick);
			dirNameView.addView(dirNameElement);
			if(d.ll(5)) d.l(String.format("element name=%s, path=%s", name, path));
		}

		void openContextMenu() {
			d.l(4,"openContextMenu");
			if(!K.blocked()) d.getAct().openContextMenu(menu); }
	}

	/**
	 * výčet menu entries, ze kterých se setavují menu jednotlivých panelů
	 */
	enum PanelMenuItem {
		SelectAll("select all") { void action(PanelDirView p) { p.selectAll(); } },
		ClearSelection("clear selection") { void action(PanelDirView p) { p.clearSelected(); } },
		RefreshDirList("refresh dir list") { void action(PanelDirView p) { p.handleRefresh(); } },
		GoHome("go to home dir") { void action(PanelDirView p) { p.handleGoHome(); } },
		SizeOfSelection("size of selection") { void action(PanelDirView p) { p.handleSizeOf(); } },
		CanWrite("can write to selected") { void action(PanelDirView p) { p.handleCanWrite(); } },
		ServerCopy("server copy selected") { void action(PanelDirView p) { p.handleServerCopy(); } },
		CopyToPeer("copy to peer") { void action(PanelDirView p) { p.handlePushToPeer(); } },
		CopyFromPeer("pull from peer") { void action(PanelDirView p) { p.handlePullFromPeer(); } },
		Move("move selected") { void action(PanelDirView p) { p.handleMove(); } },
		Share("share") { void action(PanelDirView p) { p.handleShare(); } },
		Expose("expose to http") { void action(PanelDirView p) { p.handleExpose(); } },
		Hide("hide") { void action(PanelDirView p) { p.handleHideReference(); } },
		ExposeUp("upload & expose to http") { void action(PanelDirView p) { p.handleExpose(); } },
		Delete("delete selected") { void action(PanelDirView p) { p.handleDelete(); } },
		Rename("rename") { void action(PanelDirView p) { p.handleRename(); } },
		CreateDir("create diretory") { void action(PanelDirView p) { p.handleCreateDir(); } },
		SetHomeDir("set current dir as home") { void action(PanelDirView p) { p.handleSetHome(); } },
		FreeSpace("display free space") { void action(PanelDirView p) { p.handleFree(); } },
		HackUDP("fm UDP hack") { void action(PanelDirView p) { p.handleTestUDP(); } },
		HackSDcard("fm SD Card hack") { void action(PanelDirView p) { p.handleTestSDcard(); } },
		HackFS("fm FS hack") { void action(PanelDirView p) { p.handleTestFS(); } },
		HackNotif("notification hack") { void action(PanelDirView p) { p.handleTestNotif(); } },
		HackSMS("SMS hack") { void action(PanelDirView p) { p.handleTestUri("dejsem/02/image.8630.jpeg"); } },
		OrderNameAsc("by name asc...") { void action(PanelDirView p) { p.handleOrder(K.DirListOrder.NAME_ASC); } },
		OrderNameDesc("by name desc...") { void action(PanelDirView p) { p.handleOrder(K.DirListOrder.NAME_DESC); } },
		OrderSizeAsc("by size asc...") { void action(PanelDirView p) { p.handleOrder(K.DirListOrder.SIZE_ASC); } },
		OrderSizeDesc("by size desc...") { void action(PanelDirView p) { p.handleOrder(K.DirListOrder.SIZE_DESC); } },
		OrderDateAsc("by date asc...") { void action(PanelDirView p) { p.handleOrder(K.DirListOrder.DATE_ASC); } },
		OrderDateDesc("by date desc...") { void action(PanelDirView p) { p.handleOrder(K.DirListOrder.DATE_DESC); } };

		final String title;
		void action(PanelDirView panel) {};

		PanelMenuItem() { title = name(); }
		PanelMenuItem(String n) { title = n; }
	}

	D d;
	FM fm;                              // file management methods for panel
	DirListView dirView;                // view on file list
	PanelDirView otherSidePanel = null; // panel for other local/server file system
	ArrayList<PanelMenuItem> items = new ArrayList<PanelMenuItem>();

	PanelDirView(D d) {
		this.d = d.klon(this);
	}

	void refreshDirList() {
		fm.refreshFileList();
		notifyListView();
	}

	void setUpDirView() { dirView.setUpDirView(); }

	void updateDirView() { dirView.updateDirView(); }

	void handleClickedListEntry(int pos) {
		fm.setCurrListPos(pos);
		String fn = fm.getFnByPos(pos);
		String fp = fm.fullPath(fn);
		d.l(4, String.format("on list entry click: position=%d, fp=%s, context=%s", pos, fp, d.getContext()));
		if(fm.isFile(fn)) {     // open file
			handleClickedFile(fn);
		}
		else if(!K.blocked()) {     // open dir
			fm.deleteCache(fp);
			fm.stackAndEnterDir(fp);
			updateDirView();
		}
		FragFM.sweepOutNetCmd(d);
	}

	void handleClickedFile(String fp) {}

	void addMenuItem(Menu menu, PanelMenuItem i) { addMenuItem(menu, i, i.title); }

	void addMenuItem(Menu menu, PanelMenuItem i, String title) { menu.add(Menu.NONE, i.ordinal(), Menu.NONE, title); }

	Menu addSubMenu(Menu menu, String title) {
		Menu m = menu.addSubMenu(Menu.NONE, 9999, Menu.NONE, title);
		return m;
	}

	public void buildContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		Menu subMenu, subSubMenu;

		if(menuInfo != null)
			fm.setSelection(((AdapterView.AdapterContextMenuInfo) menuInfo).position);
		for(PanelMenuItem p: PanelMenuItem.values()) items.add(p.ordinal(), p);
		d.l(4, "buildContextMenu");

		addMenuItem(menu, PanelMenuItem.RefreshDirList);
		if(PanelLocalDir.class.isInstance(this)) addMenuItem(menu, PanelMenuItem.GoHome);

		subMenu = addSubMenu(menu, "selection");
		addMenuItem(subMenu, PanelMenuItem.SelectAll);
		addMenuItem(subMenu, PanelMenuItem.ClearSelection);

		subMenu = addSubMenu(menu, "get info");
		addMenuItem(subMenu, PanelMenuItem.SizeOfSelection);
		addMenuItem(subMenu, PanelMenuItem.FreeSpace);
		addMenuItem(subMenu, PanelMenuItem.CanWrite);

		subMenu = addSubMenu(menu, "directory list");
		addMenuItem(subMenu, PanelMenuItem.RefreshDirList);
		if(PanelLocalDir.class.isInstance(this)) {
			addMenuItem(subMenu, PanelMenuItem.GoHome);
			addMenuItem(subMenu, PanelMenuItem.SetHomeDir);
		}
		subMenu = addSubMenu(subMenu, "reorder list");
		addMenuItem(subMenu, PanelMenuItem.OrderNameAsc);
		addMenuItem(subMenu, PanelMenuItem.OrderNameDesc);
		addMenuItem(subMenu, PanelMenuItem.OrderSizeAsc);
		addMenuItem(subMenu, PanelMenuItem.OrderSizeDesc);
		addMenuItem(subMenu, PanelMenuItem.OrderDateAsc);
		addMenuItem(subMenu, PanelMenuItem.OrderDateDesc);

		subMenu = addSubMenu(menu, "file operations");
		if(PanelPeerDir.class.isInstance(this)) {
			addMenuItem(subMenu, PanelMenuItem.CopyToPeer);
			addMenuItem(subMenu, PanelMenuItem.CopyFromPeer);
			addMenuItem(subMenu, PanelMenuItem.Move);
			addMenuItem(subMenu, PanelMenuItem.Delete);
			addMenuItem(subMenu, PanelMenuItem.Rename);
			addMenuItem(subMenu, PanelMenuItem.Share);
			addMenuItem(subMenu, PanelMenuItem.ExposeUp);
			addMenuItem(subMenu, PanelMenuItem.CreateDir);
		}
		else if(PanelServerDir.class.isInstance(this)) {
			addMenuItem(subMenu, PanelMenuItem.ServerCopy, "download selected");
			addMenuItem(subMenu, PanelMenuItem.Move);
			addMenuItem(subMenu, PanelMenuItem.Delete);
			addMenuItem(subMenu, PanelMenuItem.Rename);
			addMenuItem(subMenu, PanelMenuItem.Expose);
			addMenuItem(subMenu, PanelMenuItem.Hide);
			addMenuItem(subMenu, PanelMenuItem.CreateDir);
		}
		else if(PanelLocalDir.class.isInstance(this)) {
			addMenuItem(subMenu, PanelMenuItem.ServerCopy, "upload selected");
			addMenuItem(subMenu, PanelMenuItem.Move);
			addMenuItem(subMenu, PanelMenuItem.Delete);
			addMenuItem(subMenu, PanelMenuItem.Rename);
			addMenuItem(subMenu, PanelMenuItem.Share);
			addMenuItem(subMenu, PanelMenuItem.ExposeUp);
			addMenuItem(subMenu, PanelMenuItem.CreateDir);
		}

		subMenu = addSubMenu(menu, "hack");
		addMenuItem(subMenu, PanelMenuItem.HackUDP);
		addMenuItem(subMenu, PanelMenuItem.HackSDcard);
		addMenuItem(subMenu, PanelMenuItem.HackFS);
		addMenuItem(subMenu, PanelMenuItem.HackNotif);
		addMenuItem(subMenu, PanelMenuItem.HackSMS);
	}

	public boolean handleContextItemSelected(MenuItem item) {
		d.l(4, "handling selected context menu item ...................................");    // log eye catcher
		if(d.ll(2)) d.l(String.format("menu item selected id=%d, title=%s", item.getItemId(), item.getTitle()));
		if(item.getItemId() < items.size()) {
			items.get(item.getItemId()).action(this);
			FragFM.sweepOutNetCmd(d);
			return true;
		}
		return false;
	}

	void handleDirUp() {
		if(!K.blocked()) {
			fm.goUp();
			FragFM.sweepOutNetCmd(d);
			updateDirView();
		}
	}

	void handleGoToDir(View v) {
		if(!K.blocked()) {
			fm.stackAndEnterDir((String)(v.getTag()));
			FragFM.sweepOutNetCmd(d);
			updateDirView();
		}
	}

	void handleGoHome() {
		if(!K.blocked()) {
			fm.stackAndEnterDir((String)(Prefs.homeDir));
			FragFM.sweepOutNetCmd(d);
			updateDirView();
		}
	}

	void handleRefresh() {
		if(!K.blocked()) {
			refreshDirList();
			FragFM.sweepOutNetCmd(d);
		}
	}

	void notifyListView() { ((BaseAdapter) dirView.dirListView.getAdapter()).notifyDataSetChanged(); }

	void handOverServerCopy(NetTaskRef netTaskRef) {}

	void clearSelected() {
		fm.clearSelected();
		notifyListView();
	}

	void selectAll() {
		fm.cwdFl.selectAll();
		notifyListView();
	}

	void handleTestUDP() {
		d.l(4, "handling fm UDP hack...");
		d.getAct().startActivity(new Intent(d.getContext(), HackUDP.class));
	}

	void handleTestSDcard() {
		d.l(4, "handling fm SD Card hack...");
		try { FragFM.localDirPanel.fm.doCreateDir("5/5/5/5/5/5/5/5/5/5/5/5/5/5/5/5/5/5/5/5"); }
		catch(Exception e) { d.lmwa(e.getMessage()); }
	}

	/**
	 * Zkouška chování FS.
	 */
	void handleTestFS() { new HackFS(d).caselessFS(); }

	void handleTestNotif() {
		d.l(4, "handling notification hack...");
		final Context c = this.d.getContext();
		NotificationManager notifManager = (NotificationManager)c.getSystemService(Context.NOTIFICATION_SERVICE);
		final Intent notifIntent = new Intent(c, HackNotifListAct.class);
		final Intent deleteIntent = new Intent(c, HackNotifListAct.class).putExtra(K.ACTION_KEY, K.TRANSFER_PIN_NOTIFICATION);
		Notification.Builder notifBuilder = new Notification.Builder(c)
				.setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("notification test")
				.setContentIntent(PendingIntent.getActivity(c, 0, notifIntent, PendingIntent.FLAG_UPDATE_CURRENT))
				.setDeleteIntent(PendingIntent.getActivity(c, 1, deleteIntent, 0));
		notifManager.notify(42, notifBuilder.build());
	}

	void handleTestUri(String uriPath) { SendUriNG.decideSendUri(uriPath); }

	void handleSizeOf() {
		try {
			final EntitySize es = fm.determineSizeOf();
			String msg = String.format("%s\nfiles: %d\ndirs: %d",
					Formatter.formatFileSize(d.getContext(), es.getTargetSize()), es.getTargetFnum(), es.getTargetDnum());
			new NoticeDialogFragment().display(d, "size of selection", msg, null);
			FragFM.sweepOutNetCmd(d);
		}
		catch(Exception n) { d.abendMsg("determine size of section", n); }
	}

	void handleServerCopy() {
		try {
			if(!NetConn.netAvailable(d)) return;
			d.l(4, "handleServerCopy, START");
			String[] selection = fm.getStrArrSelection();
			handOverServerCopy(new NetTaskRef(d, serverCopyParms(selection), fm.reckon(selection)));
			K.title.update();
			d.l(4, "handleServerCopy, HANDED over to background");
		}
		catch(K.NothingSelected n) { d.lmwa(n.getMessage()); }
		catch(K.AllPortsBusy n) { d.lmwa(n.getMessage()); }
		catch(Exception n) { d.abendMsg("copy to/from server", n); }
	}

	/**
	 * Připravuje parametry pro kopírování souborů z/na server.</br>
	 * ● u serveru objedná port pro kopírování na pozadí</br>
	 * ● do parametrů uloží port, pole se jmény vybraných souborů, jméno cílového adresáře</br>
	 * ● zaktivuje sledování průběhu přenosu
	 *
	 * @param selection the selection
	 * @return the bundle
	 * @throws Exception the exception
	 */
	Bundle serverCopyParms(String[] selection) throws Exception {
		if(selection.length == 0) throw new K.NothingSelected();
		final int port = (Integer) SrvCmd.LONGTASK.exec(d, null);
		FragFM.sweepOutNetCmd(d);
		if(port == 0) throw new K.AllPortsBusy();
		fm.clearSelected();
		final String to = otherSidePanel.fm.cwdFl.dirName;
		final Bundle parms = new Bundle();
		parms.putInt(K.PORT_KEY, port);
		parms.putStringArray(K.FILES_FROM_KEY, selection);
		parms.putString(K.FILE_TO_KEY, to);
		//FragFM.sweepOutNetCmd(d);
		K.prepTransferOverview(d);
		return parms;
	}

	void handlePushToPeer() {
		try {
			if(!NetConn.lanAvailable(d)) return;
			String[] selection = fm.getStrArrSelection();
			if(selection.length == 0) throw new K.NothingSelected();
			fm.clearSelected();     // clear selection in file list
			Bundle parms = new Bundle();
			parms.putStringArray(K.FILES_FROM_KEY, selection);
			/*TaskProgress taskProgress = new TaskProgress(d, fm.reckon(selection));*/
			K.prepTransferOverview(d);
			new PushToPeer(d, new NetTaskRef(d, parms, fm.reckon(selection))).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}
		catch(K.NothingSelected n) { d.lmwa(n.getMessage()); }
		catch(Exception e) { d.abendMsg("copy to peer", e); }
	}

	void handlePullFromPeer() {
		if(!NetConn.lanAvailable(d)) d.abendMsg(new Exception("LAN not available"));
		else {
			Bundle parms = new Bundle();
			parms.putString(K.FILE_TO_KEY, fm.cwdFl.dirName);
			K.prepTransferOverview(d);
			try { new PullFromPeer(d, new NetTaskRef(d, parms, null)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); }
			catch(Exception e) { d.abendMsg("copy from peer", e); }
		}
	}

	void handleDelete() {
		final File[] selection = fm.getArrSelection();
		if(selection.length == 0) return;
		if(d.ll(4)) d.l("delete " + selection.length + " entries");
		final String alert = String.format("%d selected items will be recursively deleted", selection.length);
		new DialogFragmentDelete().approveDelete(this,"", alert);
	}

	void handleCanWrite() {
		final File[] selection = fm.getArrSelection();
		if(selection.length == 0) return;
		d.l(String.format("file %s, writeable=%b", selection[0].getPath(), selection[0].canWrite()));
	}

	void handleShare() {
		if(!NetConn.netAvailable(d)) return;
		final File[] selection = fm.getArrSelection();
		if(selection.length == 0) return;
		final String fn = selection[0].getName();

		final String fp = fm.fullPath(fn);
		if(d.ll(4)) d.l("share: fp=" + fp);
		String mimeType = URLConnection.guessContentTypeFromName(fn);
		if(mimeType == null) mimeType = "application/octet-stream";
		URI fURI = new File(fp).toURI();
		Uri uri = new Uri.Builder()
				.scheme(fURI.getScheme())
				.encodedAuthority(fURI.getRawAuthority())
				.encodedPath(fURI.getRawPath())
				.query(fURI.getRawQuery())
				.fragment(fURI.getRawFragment())
				.build();
		Bundle b = new Bundle();
		b.putParcelable(Intent.EXTRA_STREAM, uri);
		Intent i = new Intent(Intent.ACTION_SEND).putExtras(b).setDataAndType(uri, mimeType);
		d.getContext().startActivity(Intent.createChooser(i, "share file " + fn));
	}

	/**
	 * Vystavení vybraného objektu na http-serveru.</br>
	 * ● expose se nedávkuje, vyřizuje se jen 1.vybraný</br>
	 * ● lokální objekt se na pozadí překopíruje na server do adresáře vystavených objektů
	 * ● server vrátí URL, který se umiťuje na clipboard a případně sharuje
	 */
	void handleExpose() {
		if(!NetConn.netAvailable(d)) return;
		String[] selection = fm.getStrArrSelection();
		if(selection.length == 0) return;
		try { expose(selection[0]); } catch(Exception e) { d.abendMsg("expose to http on server", e); }
	}

	/**
	 * Zakrytí objektů před http.
	 */
	void handleHideReference() {
		if(!NetConn.netAvailable(d)) return;
		String[] selection = fm.getStrArrSelection();
		if(selection.length == 0) return;
		try { hide(selection); } catch(Exception e) { d.abendMsg("hide from http on server", e); }
	}

	void expose(String selection) throws Exception {}

	void hide(String[] selection) throws Exception {}

	void handleOrder(K.DirListOrder order) {
		if(d.ll(4)) d.l("faked ordering");
	}

	void handleFree() {
		String path;
		File[] selection = fm.getArrSelection();
		if(selection.length == 0) path = fm.getCwdName();
		else path = selection[0].getPath();
		if(d.ll(4)) d.l("display free space for " + path);
		try {
			long free = fm.getFreeSpace(path);
			new NoticeDialogFragment().display(d, "free space", Formatter.formatFileSize(d.getContext(), free), null);
		}
		catch(Exception e) { d.abendMsg("expose to server", e); }
	}

	void handleRename() {
		final File[] selection = fm.getArrSelection();
		if(selection.length == 0) return;
		final String from = selection[0].getName();
		if(d.ll(4)) d.l(String.format("rename, fn=%s", from));
		new DialogFragmentEntry().enterText(this, "rename", "new name ?", from, K.FM_ACTION_RENAME);
	}

	void handleCreateDir() {
		d.l(4,"handleCreateDir");
		new DialogFragmentEntry().enterText(this, "create directory", "enter name", "", K.FM_ACTION_CREATE);
	}

	void handleSetHome() {
		new Prefs().setHome(d.getContext(), fm.cwdFl.dirName);
	}


	void handleMove() {
		try {
			if(fm.getArrSelection().length == 0) throw new K.NothingSelected();     // nothing to move
			if(d.ll(4)) d.l(String.format("prepare move, panel=%s", this));
			new DialogFragmentMoveDest().moveDest(this, fm.getCwdName());
		}
		catch(K.NothingSelected n) { d.lmwa(n.getMessage()); }
	}

	void doMove(String moveDest) {
		if(d.ll(4)) d.l(String.format("do move, moveDest=%s", moveDest));
		try {
			fm.iterateMove(moveDest);
			fm.enterDir(moveDest);
			refreshDirList();
			updateDirView();
		}
		catch(Exception e) { d.abendMsg("moving selection", e); }
	}

	// void prepTransferOverview() { if (K.transfProgress == null) K.transfProgress = new TransferOverview(d); }   // obsoleted by K.prepTransferOverview()

	void refreshNotify() {
		fm.refreshFileList();
		notifyListView();
	}
}
