/***** BEGIN LICENSE BLOCK *****
 * Version: CPL 1.0/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Common Public
 * License Version 1.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.eclipse.org/legal/cpl-v10.html
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * Copyright (C) 2006 Ola Bini <ola.bini@ki.se>
 * 
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the CPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the CPL, the GPL or the LGPL.
 ***** END LICENSE BLOCK *****/
package org.jruby.util;

import org.jruby.RubyArray;
import org.jruby.RubyNumeric;
import org.jruby.RubyString;
import org.jruby.runtime.builtin.IRubyObject;

public class StringIOImpl {
    private long pos = 0L;
    private int lineno = 0;
    private boolean eof = false;
    private StringBuffer internal;

    public StringIOImpl(final String start) {
        internal = new StringBuffer(start);
    }

    public long write(final String obj) {
        internal.append(obj);
        return obj.length();
    }

    public String slice() {
        return internal.substring((int)pos);
    }
    
    public boolean isEof() {
        return pos > length() || eof;
    }

    public int getc() {
        return internal.charAt((int)pos++);
    }

    public String gets(final String separator) {
        int ix = internal.indexOf(separator,(int)pos);
        int fudge = 0;
        if(-1 == ix) {
            ix = (int)length();
            fudge = 1;
        }
        final String line = internal.substring((int)pos,ix);
        pos = ix + separator.length() + fudge;
        lineno++;
        return line;
    }

    public long length() {
        return internal.length();
    }

    public int lineno() {
        return lineno;
    }

    public int setLineno(final int val) {
        this.lineno = val;
        return val;
    }

    public long getPos() {
        return pos;
    }

    public long pos(final long newPos) {
        this.pos = newPos;
        return newPos;
    }

    public String read(final RubyArray argsi) {
        final IRubyObject[] args = argsi.toJavaArray();
        StringBuffer str = null;
        if(args.length > 2) {
            throw new IllegalArgumentException("wrong number of arguments (" + args.length + " for 0)");
        }
        if(args.length == 2) {
            str = ((RubyString)args[1]).getValue();
        }
        boolean skip = false;
        long len = 0;
        long olen = 0;
        if(args.length >= 1) {
            if(!args[0].isNil()) {
                len = olen = ((RubyNumeric)args[0]).getLongValue();
                if(len < 0) {
                    throw new IllegalArgumentException("negative length " + len + " given");
                }
                if((len > 0 && pos >= length()) || eof) {
                    eof = true;
                    str.delete(0,str.length());
                    return null;
                }
                skip = true;
            }

        }

        if(args.length >= 0 && !skip) {
            olen = -1;
            len = length();
            if(len < pos) {
                eof = true;
                if(null == str) {
                    str = new StringBuffer();
                } else {
                    str.delete(0,str.length());
                }
                return str.toString();
            } else {
                len = len-pos;
            }
        }

        if(null == str) {
            str = new StringBuffer(internal.substring((int)pos,(int)(pos+len)));
        } else {
            final int rst = (int)(length() - pos);
            if(len > rst) {
                len = rst;
            } 
            str.replace(0,str.length(),internal.substring((int)pos,(int)(pos+len)));
        }
        
        if(null == str) {
            if(eof) {
                str = new StringBuffer();
            }
            len = 0;
        } else {
            pos += len;
        }
        
        if(olen < 0 || olen > len) {
            eof = true;
        }
        return str.toString();
    }

    public int readchar() {
        return getc();
    }

    public void rewind() {
        this.pos = 0L;
        this.lineno = 0;
    }

    public String string() {
        return internal.toString();
    }

    public void truncate(final int len) {
        this.internal.delete(len,(int)length());
    }

    public void ungetc(final int ch) {
        this.internal.insert((int)pos,(char)ch);
    }
}
