/*
 * COMMHeaderFilter.java	2011. 03. 17
 *
 * Copyright 2011 FUJITSU KOREA LTD. All rights reserved.
 * FUJITSU KOREA LTD PROPRIETARY/CONFIDENTIAL. 
 * Use is subject to license terms.
 */
package biz.comm;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;

import org.apache.log4j.Logger;

import kr.fujitsu.com.ffw.daemon.net.filter.Filter;

/** 
 * COMMHeaderFilter
 *  
 * @created  on 1.0,  11/03/17
 * @created  by oki(FUJITSU KOREA LTD.) 
 *  
 * @modified on 
 * @modified by 
 * @caused   by   
 */ 
public class COMMHeaderFilter implements Filter {
	private static Logger logger = Logger.getLogger(COMMHeaderFilter.class);
	
	public Object receive(InputStream in) throws Exception {
		// TODO Auto-generated method stub
		StringBuffer ret = new StringBuffer();
		String getData = "";  
		try {
  
			byte[] header = readData(in, COMMBiz.CM_LENS);
			ret.append(new String(header)); 
			 
			//logger.info("Recv Header Data " + (String)ret.toString() );

			int len = Integer.parseInt(new String(header).substring(0,6));
			byte[] temp = readData(in, len);
			ret.append(new String(temp));
			
			//logger.info("Recv Body Data " + (String)ret.toString() );

			if (ret.length()>0){
				getData=(String)ret.toString();
			} 
		} catch (Exception e) {
			//029=HOST APPL ERR
			logger.error("[ERROR]:receive error:: " + e.getMessage());
			logger.error("[ERROR]:receive data:: " + (String)ret.toString());
		}
 
		return getData;
	}

	public Object receive(InputStream in, int len) throws Exception {
		// TODO Auto-generated method stub
		throw new Exception("UnImplementedException.");

		//return readData(in, len);
	}

	public Object receive(InputStream in, int offset, int len) throws Exception {
		// TODO Auto-generated method stub
		throw new Exception("UnImplementedException.");
	}

	public boolean send(OutputStream out, Object data) throws Exception {
		// TODO Auto-generated method stub
		PrintWriter pw = null;
		boolean isOk = false;
		try {
			if (pw == null)
				pw = new PrintWriter(out);
	
			pw.write((String)data);
			pw.flush();
			if (!pw.checkError()) 
				isOk=true;
			else 
				throw new Exception("java.net.SocketException: Connection " +
						"reset by peer: socket write error");
		} catch (Exception e) {
			throw e;
		}
		
		return isOk;
	}

	public boolean send(OutputStream out, int len, Object data) throws Exception {
		// TODO Auto-generated method stub
		throw new Exception("UnImplementedException.");
	}

	public boolean send(OutputStream out, int offset, int len, Object data)
			throws Exception {
		// TODO Auto-generated method stub
		throw new Exception("UnImplementedException.");
	}

	public void close() {
		// TODO Auto-generated method stub
		
	}
 	
//	public static char[] readData(InputStream in, int len) throws Exception {
//		int bcount = 0, n = 0, read_retry_count = 0;
//		char buf[] = new char[len];
//		//Reader ir = new InputStreamReader(in, "UTF-8");
//		BufferedReader br
//		   = new BufferedReader(new InputStreamReader(in, "UTF-8"));
//		for (;;) {
//			n = br.read(buf, bcount, len - bcount);
//			if (n > 0)
//				bcount += n;
//			else if (n < 0)
//				break;
//		}
//
//		return buf;
//	}

	public static byte[] readData(InputStream in, int len) throws Exception {
		
		// debug 용 코드 추가 시작
		StringBuffer buffer = new StringBuffer();
		String getData = "";  
		
		int bcount = 0, n = 0, read_retry_count = 0;
		byte buf[] = new byte[len];
		while (bcount < len) {
			n = in.read(buf, bcount, len - bcount); 
			
			/* 
			 * String str  = new String(buf,0,bcount);  
			logger.info("Recv debug Data "  + n + " -------   " + (String)str.toString() );
			buffer.append(new String(buf, bcount, len - bcount));
			*/
			if (n > 0)
				bcount += n;
			else if (n == -1)
				throw new Exception(
						"inputstream has returned an unexpected EOF");
			else if (n == 0 && ++read_retry_count == 10)
				throw new Exception(
						"inputstream-read-retry-count( 10) exceed !");
		}
		return buf;
	}

}
