/*
 * 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.regec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.morilib.nina.cmd.NinaInfo;
import net.morilib.nina.misc.SimpleTemplateParser;
import net.morilib.nina.translate.AbstractNinaTranslator;

public class NinaRegexCompiler {

	private static InputStream getTemplate(String lang) {
		InputStream ins;
		String s;

		s = "regex" + lang + ".nina.stemplate";
		ins = NinaRegexCompiler.class.getResourceAsStream(s);
		return ins;
	}

	/**
	 * 
	 * @param name
	 * @param regex
	 * @param lang
	 * @return
	 * @throws IOException
	 */
	public static byte[] createNinaSource(String name, String regex,
			String lang, String pkg) throws IOException {
		ByteArrayOutputStream ous;
		Map<String, String> m;
		InputStream ins;

		ous = new ByteArrayOutputStream();
		if((ins = getTemplate(lang)) == null) {
			return null;
		}

		m = new HashMap<String, String>();
		m.put("lang", lang);
		m.put("regex", regex.replaceAll("/", "\\\\/"));
		m.put("classname", name);
		m.put("pkg", pkg);
		SimpleTemplateParser.apply(ins, ous, m);
		return ous.toByteArray();
	}

	/**
	 * 
	 * @param name
	 * @param regex
	 * @param lang
	 * @param info
	 * @param pr
	 * @throws IOException 
	 */
	public static void createTargetSource(String name, String regex,
			String lang, String pkg, NinaInfo info,
			PrintStream pr) throws IOException {
		AbstractNinaTranslator t;
		Reader rd = null;
		byte[] a;

		try {
			if((a = createNinaSource(name, regex, lang, pkg)) == null) {
				throw new RegexCompilerException("unsupported language");
			}
			rd = new InputStreamReader(new ByteArrayInputStream(a));
			t  = AbstractNinaTranslator.getTranslator(lang);
			t.translate(name + ".nina", rd, info,
					new ArrayList<String>(),
					new HashMap<String, String>(), pr);
		} finally {
			if(rd != null) {
				rd.close();
			}
			pr.flush();
		}
	}

}
