package hh.dejsem.fm;

import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.io.File;

import hh.dejsem.K;
import hh.dejsem.Prefs;
import hh.dejsem.net.NetChOps;
import hh.dejsem.net.FileIO;
import hh.lib.D;
import hh.lib.DF;

/**
 * Fragment for File Manager operations
 */
public class FragFM extends DF {

	static FragFM instantiate(D d, FragFM f) {
		// jemná nuance:
		// new D() se odstřihne od prefixu callera (ale musí se přenést activity)
		// d.klon() prefix převezme
//		f.d = new D(f);
//		f.d.setAct(d.getAct());
		f.d = d.klon(f);
		return f;
	}

	public static void refreshNotify(boolean localFS) {
		final Class baseClass = localFS ? PanelLocalDir.class : PanelServerDir.class;
		final PanelDirView panel = localFS ? localDirPanel : remoteDirPanel;
		panel.refreshNotify();
		if(dialogDirPanel != null && baseClass.isInstance(dialogDirPanel)) dialogDirPanel.refreshNotify();
	}

	static final String TITLETEXT = "files";
	static PanelDirView localDirPanel, remoteDirPanel, dialogDirPanel;
	LinearLayout fmLayout;
	int netUsage = 0;   // <== NEW

	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		return fmLayout;
	}

	@Override
	public void onResume() {
		super.onResume();
		setUserVisibleHint(false);
		K.title.setText(TITLETEXT).update();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		sweepOutNetCmd(d);
	}

	@Override
	public boolean handleMessage(Message msg) {
		if (d.ll(4)) d.l("handle message in FragFM, what=" + msg.what);
		switch(msg.what) {
			case K.MSG_TEST:
				if(d.ll(5)) d.l("TEST from svc");
				return true;
			case K.MSG_SVC_ABEND:
				if(d.ll(5)) d.l("ABEND from svc");
				d.abendMsg((String)msg.obj, null);
				return true;
		}
		return super.handleMessage(msg);
	}

	static String getCachedCwdName(D d, String key) {
		return Prefs.sp.getString(key, null);
	}

	static String getCachedCwdName(D d, File cacheFile) throws Exception {
		String cwd = null;
		FileIO fio = null;
		if(cacheFile.exists() && (fio = new FileIO(d, cacheFile, "r")) != null) {
			try { cwd = NetChOps.getStr(d, fio); }
			catch(Exception e) { throw new Exception("get cached cwdFl name", e); }
			finally { fio.close(); } }
		return cwd;
	}

//	synchronized void netUsageIncr() { netUsage++; netInUse = true; };

//	synchronized void netUsageDecr() { if(netUsage > 0) netUsage--; netInUse = (netUsage > 0); };

	static void sweepOutNetCmd(D d) {
//		netUsageDecr();
//		if(!netInUse) d.closeCmdConn();
		K.cmdConnClose(d);
	}
}







