package kr.ac.kaist.swrc.jhannanum.module.unknown;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;

import kr.ac.kaist.swrc.jhannanum.module.Module;

public class UnknownProcessor implements Module {
	private String processing[] = new String[2000];		// 가능한 태거 후보의 갯수
	private int p_end=0;

	private BufferedReader in = null;
	private PrintWriter out = null;
	
	final static private String MODULE_NAME = "UnknownProcessor";

	String[] rules = {"ncn", "nq"};

	private void action() {
		int i;

		if (p_end==0)
			return;

		out.write(processing[0] + '\n');

		for (i = 1; i < p_end; i++)
			out.write(processing[i] + '\n');

		out.write('\n');
		p_end=0;

		out.flush();
	}

	public String getName() {
		return MODULE_NAME;
	}

	public void initialize(Reader in, Writer out, String configFile) throws Exception {
		if (in != null) {
			this.in = new BufferedReader(in);
		} else {
			this.in = null;
		}

		if (out != null) {
			this.out = new PrintWriter(out);
		} else {
			this.out = null;
		}
	}

	private boolean is_unk(String str) {
		return str.matches("^.*(?!\\\\)./unk.*$");
	}

	private void morph_in (String str) {

		processing[p_end] = str;
		p_end++;
	}
	
	private void rewriting(String str) {
		String buf = null;

		for (int i = 0; i < rules.length; i++) {
			for (int idx = str.indexOf("/unk", 0); idx != -1; idx = str.indexOf("/unk", idx + 1)) {
				if (idx > 0 && str.charAt(idx - 1) == '\\') {
					continue;
				}
				buf = str.substring(0, idx + 1) + rules[i] + str.substring(idx + 4); 
			}
			processing[p_end++] = buf;
		}
	}

	public void run() throws Exception {
		String line = null;
		boolean flag = true;

		p_end=0;

		while ((line = in.readLine()) != null) {
			if (line.length() == 0) {
				action();
			} else if (flag && p_end != 0 && line.charAt(0) == '\t') {
				if (is_unk(line)) {
					/* unk 처리를 첫번째 후보(가장 긴 형태소)에 대해서만 수행한다. */
					processing[0] = '@' + processing[0].substring(1);
					rewriting(line);
					flag = false;
				} else {
					morph_in(line);
				}
			} else {
				word_in(line);
				flag = true;
			}
		}
		action();
	}

	public void setReader(Reader in) {
		if (in != null) {
			this.in = new BufferedReader(in);
		} else {
			this.in = null;
		}
	}

	public void setWriter(Writer out) {
		if (out != null) {
			this.out = new PrintWriter(out);
		} else {
			this.out = null;
		}
	}

	public void shutdown() {

	}

	private void word_in (String str) {
		if (p_end != 0) {
			action();
		}
		processing[0] = str;
		p_end = 1;
	}
}
