/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * 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.
 *
 * The Original Code is JIM.
 *
 * The Initial Developer of the Original Code is
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * Portions created by the Initial Developer are Copyright (C) 2003
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * Pawel Chmielowski <prefiks@o2.pl>
 *
 * ***** END LICENSE BLOCK ***** */

/**
 * io.Reader
 *
 *
 */
ML.load('utils/exception.js');
ML.load('io/charsetcoder.js');

/**
 * Reader
 *
 * Constructor:
 *   Reader(uriString, encoding)
 *
 * Fields:
 *   uri
 *   uriString
 *
 * Methods:
 *   open()
 *   read([len])
 *   close()
 *
 */

function Reader(uriString)
{
    const classes = Components.classes;
    const interfaces = Components.interfaces;
    var ios = classes["@mozilla.org/network/io-service;1"].
        getService(interfaces.nsIIOService);
    var tmp, i;

    if (uriString) {
        if (typeof(uriString) == 'object') {
            tmp = uriString[0];
            for (i = 1; i < uriString.length; i++) {
                tmp += "/"+uriString[i];
            }
            uriString = tmp;
        }
        try {
            this.uri = ios.newURI(uriString, null, null);
        } catch (ex) {
            throw new IOException("reader.unable_to_get_uri", ex);
        }
    }
}

function IOException(type, reason)
{
    this.base = Exception;
    this.base(type, reason);
}

IOException.prototype =
{
    __proto__: Exception.prototype
}

Reader.prototype =
{
    __channel: null,
    __reader: null,
    __encoder: null,

    get available ()
    {
        if (this.__inputStream)
            return this.__inputStream.available();
        return 0;
    },

    open: function(charset)
    {
        this.setCharset(charset);

        var ios = Components.classes["@mozilla.org/network/io-service;1"].
            getService(Components.interfaces.nsIIOService);

        if (!(this.channel = ios.newChannelFromURI(this.uri)))
            throw { code: JIM_ERROR_IO_GETTING_CHANNEL };
        try {
            this.__bufferedStream = Components.classes["@mozilla.org/network/buffered-input-stream;1"].
                createInstance(Components.interfaces.nsIBufferedInputStream);

            this.__bufferedStream.QueryInterface(Components.interfaces.nsISeekableStream);

            this.__inputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].
                createInstance(Components.interfaces.nsIScriptableInputStream);

            this.__bufferedStream.init(this.channel.open(), 8192);
            this.__inputStream.init(this.__bufferedStream);
        } catch (ex) {
            throw new IOException("reader.unable_to_get_input_stream", ex);
        }

        if (!this.__inputStream)
            throw new IOException("reader.unable_to_get_input_stream");
    },

    setCharset: function(charset)
    {
        if (charset) {
            if (this.__coder)
                this.__coder.encoding = charset;
            else
                this.__coder = new CharsetCoder(charset);
        } else
            this.__coder = null;
    },

    read: function(len)
    {
        var ret = "";
        var r;
        var cl;

        if (!len || len > this.__inputStream.available())
            len = this.__inputStream.available();

        try {
            while (len > 0) {
                cl = len > 8192 ? 8192 : len;
                r=this.__inputStream.read(cl);
                ret += r;

                if (r.length < cl) {
                    this.__bufferedStream.seek(1, r.length - cl + 1);
                    ret += "\0";
                    len -= r.length + 1;
                } else
                    len -= cl;
            }
        } catch (ex) {
            throw new IOException("reader.read_error", ex);
        }

        if (this.__coder)
            return this.__coder.decode(ret);
        return ret;
    },

    close: function()
    {
        if (this.__inputStream)
            this.__inputStream.close();
        this.__inputStream = null;
    }
}