#include "Reader.h"

#include "Text.h"

using namespace Framework;

//! \param buffer The buffer to be read
//! \param length The length of the buffer
//! \param deleteBuffer true if the buffer should be automatically deleted
//! with delete[]
ByteArrayReader::ByteArrayReader(
    const char* buffer, int length, bool deleteBuffer)
    : ReferenceCounter(),
      length(length),
      buffer(buffer),
      deleteBuffer(deleteBuffer),
      position(0)
{}

ByteArrayReader::~ByteArrayReader()
{
    if (deleteBuffer) delete[] buffer;
}

//! Reads from the resource
//! \param bytes An array to be filled with bytes from the resource
//! \param len How many bytes should be read from the resource
void ByteArrayReader::read(char* bytes, int len)
{
    if (position < length)
        memcpy(bytes, buffer + position, MIN(len, length - position));
    position = MIN(position + len, length);
}

//! Reads the next line of the resource
//! \return The read line as Text with line break
Text* ByteArrayReader::readLine()
{
    if (position >= length) return 0;
    int start = position;
    for (; buffer[position] != '\n' && position < length; position++)
        ;
    Text* ret = new Text("");
    ret->fillText('\0', position - start + 1);
    read((char*)ret->getText(), position - start + 1);
    return ret;
}

//! Checks whether the resource has been fully read
//!  return 1 if the resource has been fully read. 0 otherwise
bool ByteArrayReader::isEnd() const
{
    return position >= length;
}

//! Sets the position of the byte to be read next
//! \param pos The index of the byte
//! \param ende 1 if the index counts from the end of the resource. 0 if the
//! index counts from the beginning of the resource
void ByteArrayReader::setReadPosition(__int64 pos, bool ende)
{
    position = ende ? MAX(length - (int)pos, 0) : MIN((int)pos, length);
}

//! Returns the index of the byte from the resource that would be read next
//! return -1 if an error occurred. Otherwise the position of the read pointer
__int64 ByteArrayReader::getReadPosition() const
{
    return position;
}

//! Returns the number of bytes to be read
__int64 ByteArrayReader::getSize() const
{
    return length;
}