/* $Id: ExtendedHTMLReader.java 125 2011-03-09 09:49:51Z ohura $ */
/*****************************************************
 * ExtendedHTMLReader
 * Copyright(C) 2008 NorthGrid Corporation
 * SMART_GS_NG 
 * 
 *   作成日   2008/10/13
 *   作成者   菊池 敏幸
 *   
 ****************************************************/
package com.hexidec.ekit.component;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.CharBuffer;

public class ExtendedHTMLReader extends Reader {

	protected Reader base = null;

	public ExtendedHTMLReader(Reader org, boolean removeHeader){
		if( removeHeader ){
			StringBuffer sb = new StringBuffer();
			char [] buffer = new char[4096];
			try{
				while(true){
					int len = org.read(buffer);
					if(len<=0) break;
					sb.append(buffer, 0, len);
				}
			}catch(IOException e){}
			String source = sb.toString();
			source = source.replaceAll("\\<head\\>(?s).*\\</head\\>", "");
			base = new StringReader(source);
		}else{
			this.base = org;
		}
	}
	
	public ExtendedHTMLReader(Reader base){
		this.base = base;
	}
	
	@Override
	public void close() throws IOException {
		base.close();
	}

	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		int count = 0;
		for(int i = 0; i < len; i++){
			int rtn = read();
			if(rtn == -1){
				return count;
			}
			cbuf[off+i] = (char)rtn;
			count++;
		}
		return count;
	}

	@Override
	public void mark(int readAheadLimit) throws IOException {
		base.mark(readAheadLimit);
	}

	@Override
	public boolean markSupported() {
		return base.markSupported();
	}

	@Override
	public int read() throws IOException {
		int rtn = 0;
		while(true){
			rtn = base.read();
			//System.out.print((char)rtn);
			if(rtn != '\n' && rtn != '\r') break;
		}
		return rtn;
	}

	@Override
	public int read(char[] cbuf) throws IOException {
		return read(cbuf, 0, cbuf.length);
	}

	@Override
	public int read(CharBuffer target) throws IOException {
		throw new IOException();
	}

	@Override
	public boolean ready() throws IOException {
		return base.ready();
	}

	@Override
	public void reset() throws IOException {
		base.reset();
	}

	@Override
	public long skip(long n) throws IOException {
		return base.skip(n);
	}
}
