package hh.dejsem.fm;

import java.io.File;

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

/**
 * file system manager operations on local files
 */
public class FMLocal extends FM {

	FSLocal fs;

	FMLocal(D d) {
		super(d);
		fs = new FSLocal(d);
	}

	@Override
	long getFreeSpace(String path) { return new File(path).getFreeSpace(); }

	@Override
	EntitySize reckon(String[] selection) throws Exception { return FileList.reckon(selection); }

	@Override
	void doCreateDir(String dirName) throws Exception {     // dirName je relativní vůči current dir
		dirName = dirName.replaceAll(K.FN_RESERVED_CHARS_REGEX, ".");
		if(d.ll(4)) d.l(String.format("creating directory %s/%s", cwdFl.dirName, dirName));
		String fp = new File(cwdFl.dirName, dirName).getCanonicalPath();
		try {
			fs.doCreateDir(fp);
			FragFM.refreshNotify(true);
		}
		catch(K.NotCompleted n) { d.lmwa("directory " + fp + " was not created"); }
	}

	@Override
	void renameSelected(String to) throws Exception {
		final String from = getArrSelection()[0].getName();
		to = to.replaceAll(K.FN_RESERVED_CHARS_REGEX, ".");
		if(d.ll(3)) d.l("rename, from=" + from + ", to=" + to);
		File fromF = new File(cwdFl.dirName, from);
		File toF = new File(cwdFl.dirName, to);
		if(toF.exists()) d.lmwa(to + " already exists");
		else {
			try {
				fs.doRename(fromF.getCanonicalPath(), toF.getCanonicalPath());
				FragFM.refreshNotify(true);
			} catch(K.NotCompleted n) { d.lmwa("rename " + fromF.getCanonicalPath() + " to " + toF.getCanonicalPath() + " unsuccessful"); }
		}
	}

	@Override
	void doMove(String from, String to) throws Exception {
		File fromF = new File(from);
		File toF = new File(to, fromF.getName());
		if(toF.exists()) d.lmwa(toF.getCanonicalPath() + " already exists");
		else {
			if(d.ll(3)) d.l("moving from " + from + " to " + to);
			try { fs.doRename(fromF.getCanonicalPath(), toF.getCanonicalPath()); }
			catch(K.NotCompleted n) { d.lmwa("" + fromF.getCanonicalPath() + " not moved"); }
		}
	}

	@Override
	void iterateDelete() {
		try {
			recurseDelete(getArrSelection());
		} catch(Exception e) {
			d.abendMsg(e);
		}
		finally {
			FragFM.refreshNotify(true);
		}
	}

	void recurseDelete(File[] selection) throws Exception {
		for(File f: selection) {
			if(f.isDirectory()) {
				if(d.ll(3)) d.l("recurse delete: diving into " + f.getPath());
				recurseDelete(f.listFiles()); }
			doDelete(f); }
	}

	void doDelete(File f) throws Exception {
		if(d.ll(3)) d.l(String.format("deleting %s", f.getPath()));
		//if(f.getName().endsWith("C")) throw new Exception("test ABENDu");   // +++
		try { fs.doDelete(f.getCanonicalPath()); }
		catch(K.NotCompleted n) { d.lmwa(String.format("%s NOT deleted", f.getCanonicalPath())); }
	}

	@Override
	FileList createFileList(String dirName) { return cacheFileList(new LocalFileList(d, dirName)); }

	@Override
	void deleteCache(String fp) {
		cache.remove(fp);
		/*D.cacheFileL.delete();*/ }
}
