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

import java.io.PrintStream;
import java.util.ResourceBundle;

public class NinaException extends RuntimeException {

	private static final String CLSNAME =
			NinaException.class.getPackage().getName().replace(
					'.', '/');
	private static ResourceBundle msgs;

	private NinaParser parser = null;
	private Quadro quadro = null;

	static {
		msgs = ResourceBundle.getBundle(CLSNAME + "/nina_messages");
	}

	/**
	 * 
	 * @param s
	 * @param os
	 * @return
	 */
	public static String getMessage(String s, Object... os) {
		String t;

		if((t = msgs.getString(s)) != null) {
			return String.format(t, os);
		} else {
			return "unknown";
		}
	}

	/**
	 * 
	 * @param msgcode
	 * @param os
	 */
	public NinaException(String msgcode, Object... os) {
		super(getMessage(msgcode, os));
	}

	/**
	 * 
	 * @param q
	 * @param msgcode
	 * @param os
	 */
	public NinaException(NinaParser q, String msgcode,
			Object... os) {
		super(getMessage(msgcode, os));
		parser = q;
	}

	/**
	 * 
	 * @param q
	 * @param msgcode
	 * @param os
	 */
	public NinaException(Quadro q, String msgcode,
			Object... os) {
		super(getMessage(msgcode, os));
		quadro = q;
	}

	/**
	 * 
	 * @param cause
	 * @param msgcode
	 * @param os
	 */
	public NinaException(Throwable cause, String msgcode,
			Object... os) {
		super(getMessage(msgcode, os), cause);
	}

	/**
	 * 
	 * @param o
	 */
	public void printTrace(PrintStream o) {
		if(parser != null) {
			parser.printTrace(o);
		} else if(quadro != null) {
			quadro.printTrace(o);
		}
	}

}
