/*************************************************
 * 프로그램명 : StringConverter.java 프로그램설명 : Unicode 2.0 => Unicode 1.2 변환 Unicode 1.2 => Unicode 2.0 변환 KSC5601 => 8859_1
 * 변환 8859_1 => KSC5601 변환
 * 
 * 작 성 자 : 강 원 중 작 성 일 : 2002. 5.27 최신변경일 : 2002. 6.5
 **************************************************/

package kr.co.kihyun.lang;

import java.sql.*;
import java.io.*;

public class StringConverter {

	private static final boolean NO_CONVERT = true;

	/*****************************
	 * Unicode 2.0 => Unicode 1.2
	 ******************************/
	public static String toDB(String uni20) throws SQLException {
		if (uni20 == null)
			return null;
		int len = uni20.length();
		char[] out = new char[len];
		for (int i = 0; i < len; i++) {
			char c = uni20.charAt(i);
			if (c < 0xac00 || c > 0xd7a3) {
				out[i] = c;
			} else { // Unicode 2.0 한글코드 영역
				try {
					byte[] ksc = String.valueOf(c).getBytes("KSC5601");
					if (ksc.length != 2) {
						out[i] = '\ufffd';
						System.err.println("Warning : Some of Unicode 2.0 Hangul Character was ignored.");
					} else {
						out[i] = (char) (0x3400 + ((ksc[0] & 0xff) - 0xb0) * 94 + (ksc[1] & 0xff) - 0xa1);
					}
				} catch (java.io.UnsupportedEncodingException ex) {
					throw new SQLException(ex.getMessage());
				}
			}
		}
		return new String(out);
	}

	/*****************************
	 * Unicode 2.0 --> Unicode 1.2
	 ******************************/
	public static String fromDB(String uni12) throws SQLException {
		if (uni12 == null)
			return null;
		int len = uni12.length();
		char[] out = new char[len];
		byte[] ksc = new byte[2];
		for (int i = 0; i < len; i++) {
			char c = uni12.charAt(i);
			if (c < 0x3400 || c > 0x4dff) {
				out[i] = c;
			} else if (c >= 0x3d2e) { // Unicode 1.2 한글 보충영역 A, B
				out[i] = '\ufffd';
				System.err.println("Warning : Some of Unicode 1.2 Hangul Character was ignored.");
			} else { // Unicode 1.2의 KSC5601 대응 한글 영역
				try {
					ksc[0] = (byte) ((c - 0x3400) / 94 + 0xb0);
					ksc[1] = (byte) ((c - 0x3400) % 94 + 0xa1);
					out[i] = new String(ksc, "KSC5601").charAt(0);
				} catch (java.io.UnsupportedEncodingException ex) {
					throw new SQLException(ex.getMessage());
				}
			}
		}
		return new String(out);
	}

	/****************************
	 * KSC5601 => 8859_1 으로 변환
	 *****************************/
	public static String toEng(String ko) throws SQLException {
		return toEng(ko, NO_CONVERT);
	}

	public static String toEng(String ko, boolean convert) throws SQLException {
		if (convert) {
			if (ko == null) {
				return null;
			}
			String new_str = null;
			try {
				new_str = new String(ko.getBytes("KSC5601"), "8859_1");
			} catch (UnsupportedEncodingException ex) {
				throw new SQLException(ex.getMessage());
			}
			return new_str;
		} else {
			return ko;
		}
	}

	/****************************
	 * 8859_1 => KSC5601으로 변환
	 *****************************/
	public static String toKor(String en) throws SQLException {
		return toKor(en, NO_CONVERT);
	}

	public static String toKor(String en, boolean convert) throws SQLException {
		if (convert) {
			if (en == null) {
				return null;
			}
			String new_str = null;
			try {
				new_str = new String(en.getBytes("8859_1"), "KSC5601");
			} catch (UnsupportedEncodingException ex) {
				throw new SQLException(ex.getMessage());
			}
			return new_str;
		} else {
			return en;
		}
	}

	public static String toHtmlBr(String str) {
		CharArrayReader chr;
		BufferedReader inDesc;
		String line;
		StringBuffer newDesc = new StringBuffer();

		try {
			// detalDesc를 보기 좋게 변경
			chr = new CharArrayReader(str.toCharArray());
			inDesc = new BufferedReader(chr);

                        //v2 36.경쟁조건 : 검사시점과 사용시점 (File)_CWE-367 : Update by YOUNGJUN,CHO
			/*
                        line = inDesc.readLine();
			while (line != null) {
				newDesc.append(line);
				newDesc.append("<br>");
				line = inDesc.readLine();
			}
                        */
			while ((line = inDesc.readLine()) != null) {
				newDesc.append(line);
				newDesc.append("<br>");
			}
                        //================================================
                        
			str = newDesc.toString();
			inDesc.close();
			return str;
		} catch (IOException ex) {
			System.out.println("error message : " + ex);
			return str;
		}
	}

	public static String toOneLine(String str) {
		CharArrayReader chr;
		BufferedReader inDesc;
		String line;
		String newDesc = "";

		try {
			// detalDesc를 보기 좋게 변경
			chr = new CharArrayReader(str.toCharArray());
			inDesc = new BufferedReader(chr);

                        //v2 36.경쟁조건 : 검사시점과 사용시점 (File)_CWE-367 : Update by YOUNGJUN,CHO
			/*
                        line = inDesc.readLine();
			while (line != null) {
				newDesc += line;
				line = inDesc.readLine();
			}
                        */
			while ((line = inDesc.readLine()) != null) {
				newDesc += line;
			}
                        //================================================
                        
			str = newDesc;
			inDesc.close();
			return str;
		} catch (IOException ex) {
			System.out.println("error message : " + ex);
			return str;
		}
	}

	public static String toHtmlBrNbsp(String str) {
		CharArrayReader chr;
		BufferedReader inDesc;
		String line;
		String newDesc = "";

		try {
			// detalDesc를 보기 좋게 변경
			chr = new CharArrayReader(str.toCharArray());
			inDesc = new BufferedReader(chr);

                        //v2 36.경쟁조건 : 검사시점과 사용시점 (File)_CWE-367 : Update by YOUNGJUN,CHO
                        /*
			line = inDesc.readLine();
			while (line != null) {
				newDesc += line + "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
				line = inDesc.readLine();
			}
                        */
			while ((line = inDesc.readLine()) != null) {
				newDesc += line + "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
			}
                        //================================================
                        
			str = newDesc;
			inDesc.close();
			return str;
		} catch (IOException ex) {
			System.out.println("error message : " + ex);
			return str;
		}
	}

	public static int[] getArrayIndex(StringBuffer strbuf, String chr) {
		int[] arrayIndex = null;

		try {

			int count = 0;
			int lastIndex = strbuf.lastIndexOf(chr);

			// 배열 size개산
			for (int i = 0, index = 0; index < lastIndex && i < lastIndex; i++) {
				index = strbuf.indexOf("'", index + 1);
				count++;
			}

			arrayIndex = new int[count];

			// 생성된 배열에 값 insert
			for (int i = 0, index = 0; index < lastIndex && i < lastIndex; i++) {
				index = strbuf.indexOf("'", index + 1);
				arrayIndex[i] = index;
			}
			return arrayIndex;
		} catch (Exception ex) {
			return arrayIndex;
		}
	}

	// 특정 문자 삭제
	public static StringBuffer delete(StringBuffer strbuf, String chr, int[] arrayIndex) {

		for (int i = 0; i < arrayIndex.length; i++) {
			strbuf.deleteCharAt(arrayIndex[arrayIndex.length - (i + 1)]);
		}

		return strbuf;
	}

	// 특정문자 입력
	public static StringBuffer insert(StringBuffer strbuf, String chr, int[] arrayIndex) {

		for (int i = 0; i < arrayIndex.length; i++) {
			strbuf.insert(arrayIndex[arrayIndex.length - (i + 1)], chr);
		}

		return strbuf;
	}

	public static String changeChar(String contentStr, String oldStr, String newStr) {

		StringBuffer strbuf = new StringBuffer(contentStr);

		int[] arrayIndex = getArrayIndex(strbuf, oldStr);

		strbuf = delete(strbuf, oldStr, arrayIndex);
		strbuf = insert(strbuf, newStr, arrayIndex);

		return strbuf.toString();
	}

	public static String toSQL(String contentStr) {

		String oldStr = "'";
		String newStr = "'";
		int[] arrayIndex = null;

		StringBuffer strbuf = new StringBuffer(contentStr);
		// 첫번째 문자가 target 문자일경우 인식못함
		// 그래서 공백을 넣어줌
		strbuf.insert(0, " ");

		arrayIndex = getArrayIndex(strbuf, oldStr);
		strbuf = insert(strbuf, newStr, arrayIndex);

		// 공백을 넣으준것을 삭제
		strbuf.delete(0, 1);
		return strbuf.toString();
	}

	/*
	 * public static void main(String[] args){ String sql = "'안녕하세요'\n"+ "'\n"+ "'\n"+ "'\n"+ "'\n"+ "'\n"+ "'안녕하세요''";
	 * 
	 * //StringBuffer strbuf = new StringBuffer(sql);
	 * 
	 * //StringConverter.getArrayIndex(strbuf, "'"); //StringConverter.delete(strbuf, "'");
	 * //System.out.println(StringConverter.changeChar(sql, "'", "\"")); System.out.println("\n\nsql1 : \n" + sql);
	 * System.out.println("\n\nsql4 : \n" + StringConverter.toSql(sql)); }
	 */
}
