/*
 * 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 ShMsgbox implements ShProcess {

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

		System.arraycopy(args, 1, a, 0, a.length);
		o = new OptionIterator("cyYqiwe", a);
		while(o.hasNext()) {
			switch(o.nextChar()) {
			case 'c':  opt = JOptionPane.OK_CANCEL_OPTION;  break;
			case 'y':  opt = JOptionPane.YES_NO_OPTION;  break;
			case 'Y':  opt = JOptionPane.YES_NO_CANCEL_OPTION;  break;
			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();
			r = JOptionPane.showOptionDialog(null, msg, tle, opt, mes,
					null, null, null);
			if(r == JOptionPane.YES_OPTION ||
					r == JOptionPane.OK_OPTION) {
				return 0;
			} else if(r == JOptionPane.NO_OPTION) {
				return 1;
			} else if(r == JOptionPane.CANCEL_OPTION) {
				return 2;
			} else {
				return 72;
			}
		} catch(HeadlessException e) {
			err.println("msgbox: GUI is not available.");
			return 72;
		}
	}

}
