package ch.wlkl.shell;

class ExtFD<T> extends Cat<T> {
	String ext = null;
	String extOpt = null;
	Cat in = null;
	Cat out = null;
	char state = 'e';

	public ExtFD () {
	}

	/**
	 * return a new Cat as the concatenation of args, using {@link #reset(Object[])}
	 */
	public ExtFD (Object... args) {
		this();
		reset(args);
	}
	
	public void reset (Object... args) {
		close();
		ext = extOpt = null;
		in = out = null;
		state = 'e';
		addIo(args);
	}

	public void addIo(Object... args) {
		String opt = " ";
		String o1 = " ";
		for (Object obj : args) {
			if (null != (o1 = Option.single(obj))) {
				opt = normalizeOpt(o1).replace(eContinue, ' ');
			} else if (state == 'e') {
				if (opt.charAt(0) != eExtFD)
					fail("first opt not ext " + opt);
				extOpt = opt;
				ext = (String) obj;
			} else if (opt.charAt(0) == 'r' || (opt.charAt(0) == ' ' && state == 'R')) {
				if (state == 'R')
					in.addIo(opt, obj);
				else if (in == null)
					in = new Cat(opt, obj);
				else
					fail("bad < > change");
				state = 'R';
			} else if ("wa".indexOf(opt.charAt(0)) >= 0 || (opt.charAt(0) == ' ' && state == 'W')) {
				if (state == 'W')
					out.addIo(opt, obj);
				else if (out == null)
					out = new Cat(opt, obj);
				else
					fail("bad < > change");
				state = 'W';
			} else {
				fail("bad opt " + opt);				
			}
		}
	}
	public void open(String opt) {
		close();
		state = 'o';
		if (in != null) {
			say("copying in to " + extOpt + " " + ext);
		}
	}

	public void close() {
		if (state == 'o' && out != null) {
			say("copying " + extOpt + " " + ext + " to out " + out);			
		}
		state = ' ';
		say("copying in to " + extOpt + " " + ext);
	}
	public void write(T line) {
		fail("write to ExtFD");
	}

	public T read() {
		fail("read ExtFD");
		return null;
	}
}

