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

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

/**
 *
 *
 * @author MORIGUCHI, Yuichiro 2013/11/02
 */
public final class CharCodes {

	private CharCodes() {}

	/**
	 * 
	 * @param c
	 * @param cset
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static int unicodeToOtherCode(char c,
			String cset) throws UnsupportedEncodingException {
		ByteArrayInputStream b;
		InputStreamReader r;
		String s;
		char[] a;
		int x;

		if(cset == null || cset.equals("") || cset.equals("UTF-8")) {
			return c;
		} else if(c < 128) {
			return c;
		} else {
			a = new char[1];
			a[0] = c;
			s = new String(a);
		}

		try {
			b = new ByteArrayInputStream(s.getBytes());
			r = new InputStreamReader(b, cset);
			x = r.read();
			return x;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
