/*
 * 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.awt.HeadlessException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Iterator;

import javax.swing.JOptionPane;

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

public class ShWread implements ShProcess {

	public int main(ShEnvironment env, ShFileSystem fs, InputStream in,
			PrintStream out, PrintStream err,
			String... args) throws IOException {
		String r, msg = "?", tle = "jsh dialog", var = "WREAD";
		String[] a = new String[args.length - 1];
		int mes = JOptionPane.PLAIN_MESSAGE;
		Iterator<String> t;
		OptionIterator o;

		System.arraycopy(args, 1, a, 0, a.length);
		o = new OptionIterator("qiwe", a);
		while(o.hasNext()) {
			switch(o.nextChar()) {
			case 'q':  mes = JOptionPane.QUESTION_MESSAGE;  break;
			case 'i':  mes = JOptionPane.INFORMATION_MESSAGE;  break;
			case 'w':  mes = JOptionPane.WARNING_MESSAGE;  break;
			case 'e':  mes = JOptionPane.ERROR_MESSAGE;  break;
			}
		}

		try {
			t = o.filenameIterator();
			if(t.hasNext())  msg = t.next();
			if(t.hasNext())  tle = t.next();
			if(t.hasNext())  var = t.next();
			r = JOptionPane.showInputDialog(null, msg, tle, mes);
			if(r != null) {
				env.bind(var, r);
			} else {
				env.unbind(var);
			}
			return 0;
		} catch(HeadlessException e) {
			err.println("wread: GUI is not available.");
			return 72;
		}
	}

}
