/*
 * TextMemoryStream.java
 * Copyright (c) 2008 kbinani
 *
 * This file is part of jp.sourceforge.lipsync.vsq.
 *
 * jp.sourceforge.lipsync.vsq is free software; you can redistribute it and/or
 * modify it under the terms of the BSD License.
 *
 * jp.sourceforge.lipsync.vsq is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
package jp.sourceforge.lipsync.vsq;

import java.io.*;
import java.util.*;

/**
 *
 * @author kbinani
 */
public class TextMemoryStream {
    StringBuilder m_ms = null;
    int m_position;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="s"></param>
    public void write( String value ) {
        m_ms.append( value );
        m_position = m_ms.length();
    }

    public void rewind() {
        m_position = 0;
    }

    public void writeLine( String s ) {
        m_ms.append( s + "\n" );
    }

    public void close() {
        if ( m_ms != null ) {
            m_ms = null;
        }
    }

    public int peek() {
        if ( m_position >= m_ms.length() ) {
            return -1;
        } else {
            return (int)m_ms.charAt( m_position );
        }
    }

    private int readByte() {
        if ( m_position >= m_ms.length() ) {
            return -1;
        } else {
            m_position++;
            return (int)m_ms.charAt( m_position );
        }
    }

    public String readLine() {
        int ret;
        ret = readByte();
        ArrayList buffer = new ArrayList();
        while ( ret >= 0 ) {
            char ch = (char)ret;
            if ( ch == '\n' ) {
                int next;
                long current = m_position; //0x0Dを検出した直後のストリームの位置

                break;
            }
            buffer.add( ch );
            ret = readByte();
        }
        String ans = "";
        for ( int i = 0; i < buffer.size(); i++ ) {
            ans += buffer.get( i );
        }
        return ans;
    }

    public void dispose() {
        close();
    }

    public TextMemoryStream( String path, String encoding ) throws Exception {
        m_ms = new StringBuilder();
        File f = new File( path );
        if ( f.exists() ) {
            FileReader fis = new FileReader( f );
            BufferedReader br = new BufferedReader( fis );
            while ( br.ready() ) {
                String line = br.readLine();
                m_ms.append( line + "\n" );
            }
        }
        m_position = 0;
    }

    public TextMemoryStream() {
        m_ms = new StringBuilder();
        m_position = 0;
    }

}
