#include "nsCLABScriptableInputStream.h"
#include "nsCOMPtr.h"

#include "nsComponentManagerUtils.h"
#include "nsMemory.h"

NS_IMPL_ISUPPORTS1(nsCLABScriptableInputStream, nsICLABScriptableInputStream)

nsCLABScriptableInputStream::nsCLABScriptableInputStream()
{
  /* member initializers and constructor code */
}

nsCLABScriptableInputStream::~nsCLABScriptableInputStream()
{
  /* destructor code */
}

/* void close (); */
NS_IMETHODIMP nsCLABScriptableInputStream::Close()
{
    if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
    return mInputStream->Close();
}

/* void init (in nsIInputStream aInputStream); */
NS_IMETHODIMP nsCLABScriptableInputStream::Init(nsIInputStream *aInputStream)
{
    if (!aInputStream) return NS_ERROR_NULL_POINTER;
    mInputStream = aInputStream;
    return NS_OK;
}

/* unsigned long available (); */
NS_IMETHODIMP nsCLABScriptableInputStream::Available(PRUint32 *_retval)
{
    if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;
    return mInputStream->Available(_retval);
}

/* void read (in unsigned long aCount, out unsigned long aLen, [size_is (aLen), retval] out string data); */
NS_IMETHODIMP nsCLABScriptableInputStream::Read(PRUint32 aCount, PRUint32 *aLen, char **data)
{
    nsresult rv = NS_OK;
    PRUint32 count = 0;
    char *buffer = nsnull;

    if (!mInputStream) return NS_ERROR_NOT_INITIALIZED;

    rv = mInputStream->Available(&count);
    if (NS_FAILED(rv)) return rv;

    count = PR_MIN(count, aCount);
    buffer = (char*)nsMemory::Alloc(count);
    if (!buffer) return NS_ERROR_OUT_OF_MEMORY;

    PRUint32 amtRead = 0;
    rv = mInputStream->Read(buffer, count, &amtRead);
    if (NS_FAILED(rv)) {
        nsMemory::Free(buffer);
        return rv;
    }

    *data = buffer;
    *aLen = amtRead;

    return NS_OK;
}
