/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   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 org.bodington.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

/**
 * Class to allow a file to be treated as a CharSequence.
 * At the moment it just buffers the whole file in memory but we could
 * have it scan the file to get then length and then hope the person wants
 * chunks in order. 
 * @author buckett
 */
public class ReaderCharSequence implements CharSequence
{
    private Reader source;
    private StringBuffer buffer;
    
    public ReaderCharSequence(Reader reader) throws IOException
    {
        // Only Buffer if we aren't already
        if (reader instanceof BufferedReader)
            this.source = reader;
        else
            this.source = new BufferedReader(reader);
        
        buffer = new StringBuffer();
        char buf[] = new char[1024];
        int read;
        while ((read = source.read(buf)) != -1)
            buffer.append(buf,0,read);
    }

    public int length()
    {
        return buffer.length();
    }

    public char charAt(int index)
    {
        return buffer.charAt(index);
    }

    public CharSequence subSequence(int start, int end)
    {
        return buffer.subSequence(start, end);
    }
    
    public String toString()
    {
        return buffer.toString();
    }

}
