/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.morilib.sh.builtin;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.util.Iterator;

import net.morilib.sh.ShEnvironment;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;
import net.morilib.sh.misc.IOs;
import net.morilib.unix.misc.OptionIterator;
import net.morilib.unix.misc.TrReader;

public class ShTr implements ShProcess {

	public int main(ShEnvironment env, ShFileSystem fs, InputStream in,
			PrintStream out, PrintStream err,
			String... args) throws IOException {
		String[] a = new String[args.length - 1];
		String sq = null, t1 = null, t2 = null;
		boolean complement = false;
		boolean truncate = false;
		boolean squeeze = false;
		boolean delete = false;
		Iterator<String> t;
		OptionIterator o;
		TrReader rd;
		Writer wr;

		System.arraycopy(args, 1, a, 0, a.length);
		o = new OptionIterator("cdst", a);
		while(o.hasNext()) {
			switch(o.nextChar()) {
			case 'c':  complement = true;  break;
			case 'd':  delete = true;  break;
			case 's':  squeeze = true;  break;
			case 't':  truncate = true;  break;
			}
		}

		t = o.filenameIterator();
		if(delete) {
			if(truncate) {
				err.println("tr: cannot truncate and delete");
				return 2;
			} else if(!t.hasNext()) {
				err.println("tr: missing delete pattern");
				return 2;
			}
			t1 = t.next();
		}

		if(squeeze) {
			if(truncate) {
				err.println("tr: cannot truncate and delete");
				return 2;
			} else if(!t.hasNext()) {
				err.println("tr: missing squeezing pattern");
				return 2;
			}
			sq = t.next();
		}

		if(t1 == null && sq == null) {
			if(!t.hasNext()) {
				err.println("tr: missing pattern1");
				return 2;
			}
			t1 = t.next();

			if(!t.hasNext()) {
				err.println("tr: missing pattern2");
				return 2;
			}
			t2 = t.next();
		}

		rd = new TrReader(new InputStreamReader(in, env.getCharset()),
				t1, t2, sq, complement, truncate);
		wr = new OutputStreamWriter(out, env.getCharset());
		IOs.copy(rd, wr);
		return 0;
	}

}
