/*
 * Copyright 2013-2014 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.nina.cmd;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.morilib.nina.NinaException;
import net.morilib.nina.regec.NinaRegexCompiler;
import net.morilib.nina.regec.RegexCompilerException;

public final class Regec {

	private static final Pattern CLSN = Pattern.compile(
			"[^\\.]+");

	private static String getClassname(String name) {
		Matcher m;

		if((m = CLSN.matcher(name)).lookingAt()) {
			return m.group();
		} else {
			throw new RegexCompilerException("invalid filename");
		}
	}

	private static String getLanguageFromSuffix(String s) {
		if(s.endsWith(".java")) {
			return "Java";
		} else {
			return null;
		}
	}

	public static void main(String[] args) {
		PrintStream p = null;
		NinatOptions o;
		String l, n;

		try {
			if(args.length < 3) {
				System.err.println("arguments too few");
				System.exit(2);
			} else if((l = getLanguageFromSuffix(args[2])) == null) {
				System.err.println("unknown language suffix");
				System.exit(2);
			} else {
				o = new NinatOptions();
				n = getClassname(args[2]);
				o.filename = n;
				p = new PrintStream(new FileOutputStream(args[2]));
				NinaRegexCompiler.createTargetSource(n, args[0], l,
						args[1], o, p);
			}
		} catch(IOException e) {
			throw new RuntimeException(e);
		} catch(NinaException e) {
			System.err.println(e.getMessage());
			System.exit(2);
		} catch(RegexCompilerException e) {
			System.err.println(e.getMessage());
			System.exit(2);
		} finally {
			if(p != null) {
				p.close();
			}
		}
	}

}
