/*
 * Copyright 2009-2010 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.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.morilib.automata.DFA;
import net.morilib.automata.NFA;
import net.morilib.automata.NFAState;
import net.morilib.math.stochastic.GenerateRandomSequence;
import net.morilib.math.stochastic.StochasticProcess;
import net.morilib.nina.Nina;
import net.morilib.nina.NinaDFAPattern;
import net.morilib.nina.NinaNFAPattern;
import net.morilib.nina.NinaException;
import net.morilib.nina.NinaNullConsole;
import net.morilib.nina.NinaPattern;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/10/19
 */
public class ZNina {

	private static final Pattern POPT = Pattern.compile(
			"-P([^=]+)=(.*)");

	private static int kanon = 0;
	private static ZNinaOptions opts;

	private static String repond(boolean b) {
		if(kanon > 0) {
			return b ? "hachimitsukumasan" : "pompokotanukisan";
		} else {
			return b ? "matched" : "no match";
		}
	}

	static int parseOptions(String[] args, Map<String, String> prms) {
		int k = 0, x;
		Matcher m;
		String s;

		for(; k < args.length; k++) {
			if((s = args[k]).startsWith("-L")) {
				opts.libs.add(s.substring(2));
			} else if((m = POPT.matcher(s)).matches()) {
				prms.put(m.group(1), m.group(2));
			} else if(!s.startsWith("--")) {
				return k;
			} else if(s.equals("--help")) {
				opts.usage();
				System.exit(2);
			} else if(s.startsWith("--libpath=")) {
				opts.libs.add(s.substring(10));
			} else if(s.equals("--kanon")) {
				kanon = 1;
			} else if((x = s.indexOf('=')) < 0) {
				opts.opts.put(s.substring(2), "");
			} else {
				opts.opts.put(s.substring(2, x), s.substring(x + 1));
			}
		}
		return k;
	}

	private static void _match(NinaPattern p) throws IOException {
		BufferedReader rd = new BufferedReader(
				new InputStreamReader(System.in));
		String s;

		System.out.print("match> ");
		while((s = rd.readLine()) != null && !s.equals("exit")) {
			System.out.println(repond(p.matcher(s).matches()));
			System.out.print("match> ");
		}
	}

	@SuppressWarnings("unchecked")
	public static void process(String arg, Map<String, String> prms) {
		Map<String, Object> sub;
		InputStream ins = null;
		Reader rd;
		Object o;
		int k;

		try {
			sub = new HashMap<String, Object>();
			ins = new FileInputStream(arg);
			rd  = new InputStreamReader(ins);
			o   = Nina.compile(arg, rd, opts.getLibraryList(), prms,
					sub, NinaNullConsole.NULL).getMachine();
			if(o instanceof DFA) {
				_match(new NinaDFAPattern(
						(DFA<Object, Object, Void>)o));
			} else if(o instanceof NFA) {
				_match(new NinaNFAPattern(
						(NFA<Object, NFAState, Void>)o));
			} else if(o instanceof StochasticProcess) {
				k = opts.getOptionInt("lines", 10);
				for(int i = 0; i < k; i++) {
					System.out.println(GenerateRandomSequence.generate(
							(StochasticProcess)o,
							opts.getOption("delimiter")));
				}
			}
			System.exit(0);
		} catch(IOException e) {
			opts.perror("ioerror");
			if(!opts.getOption("exception").equals("")) {
				e.printStackTrace(System.err);
			}
		} catch(NinaException e) {
			opts.pmessage(e.getMessage());
			if(!opts.getOption("exception").equals("")) {
				e.printTrace(System.err);
				e.printStackTrace(System.err);
			} else if(!opts.getOption("trace").equals("")) {
				e.printTrace(System.err);
			}
		} finally {
			try {
				if(ins != null) ins.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	public static void main(String[] args) {
		Map<String, String> x;
		int k;

		x = new HashMap<String, String>();
		opts = new ZNinaOptions();
		if(args.length == 0) {
			opts.usage();
			System.exit(2);
		} else if((k = parseOptions(args, x)) == args.length) {
			opts.perror("nofiles");
			System.exit(2);
		} else {
			for(; k < args.length; k++) {
				process(args[k], x);
			}
			System.exit(0);
		}
	}

}
