package hh.dejsem.fm;

import java.io.File;

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

/**
 * file system manager operations on remote files
 */
public class FMServer extends FM {

	FSServer fs;

	FMServer(D d) {
		super(d);
		fs = new FSServer(d);
	}

	@Override
	long getFreeSpace(String path) throws Exception {
		long free = (Long) SrvCmd.FREE.exec(d, null);
		FragFM.sweepOutNetCmd(((FragFM)d.getFragment()).d);
		return free;
	}

	@Override
	EntitySize reckon(String[] selection) throws Exception {
		EntitySize ds = new EntitySize();
		for(String fp: selection) {
			FileAttrs fa = getFa(new File(fp).getName());
			if(fa.isFile()) { ds.addTargetFile(fa.size); }
			else ds.add((EntitySize)SrvCmd.RECKON.exec(d, fp));
		}
		return ds;
	}

	@Override
	void doCreateDir(String dirName) {
		if(d.ll(3)) d.l("creating directory " + dirName);
		if(cwdFl.nameExists(dirName)) d.lmwa("name " + dirName + " already exists in this directory");
		else
			try {
				fs.doCreateDir(fullPath(dirName));
				FragFM.refreshNotify(false);
				FragFM.sweepOutNetCmd(((FragFM)d.getFragment()).d); }
			catch(Exception e) { d.abendMsg("create directory", e); }
	}

	@Override
	void renameSelected(String to) {
		final String from = getArrSelection()[0].getName();
		if(d.ll(3)) d.l("rename, from=" + from + ", to=" + to);
		if(cwdFl.nameExists(to)) d.abendMsg("name " + to + " already exists in this directory", null);
		else
			try {
				fs.doRename(fullPath(from), fullPath(to));
				FragFM.refreshNotify(false);
				FragFM.sweepOutNetCmd(((FragFM)d.getFragment()).d); }
			catch(Exception e) { if(!K.EntryNotFound.class.isInstance(e)) d.abendMsg("rename entry", e); }
	}

	@Override
	void doMove(String from, String to) throws Exception {
		if(d.ll(3)) d.l("moving from " + from + " to " + to);
		try { fs.doMove(from, to); }
		catch(Exception e) {
			if(K.EntryNotFound.class.isInstance(e)) {
				final String fp = new File(to).getParent();
				deleteCache(fp);
				throw new Exception(String.format("%s not found on server", fp)); }
			else d.abendMsg("move entry", e);
		}
	}

	@Override
	void iterateDelete() {
		try {
			for(File f: getArrSelection()) doDelete(f);
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			FragFM.refreshNotify(false);
		}
	}

	void doDelete(File f) {
		try {
			if(d.ll(3)) d.l(String.format("deleting %s", f.getPath()));
			fs.doDelete(f.getPath()); }
		catch(Exception e) { d.abendMsg("delete entry", e); }
	}

	/*
	@Override
	void expose(String[] selection) throws Exception {
		String uriName = (String)SrvCmd.EXPOSE.exec(this, selection[0]);
		fmsrv.sweepOutNet();
		if(uriName != null) sendSMS(uriName);
		if(d.ll(4)) l(uriName + " exposed");
	}
	*/

	@Override
	FileList createFileList(String ncwd) { return cacheFileList(new RemoteFileList(d, ncwd)); }

	@Override
	void deleteCache(String fp) {
		cache.remove(fp);
		K.cacheFileR.delete(); }
}

