/* -*- mode: c++; indent-tabs-mode: nil -*- */
/** @file QC_InputStreamLineIterator.qpp InputStreamLineIterator class definition */
/*
  Qore Programming Language

  Copyright (C) 2016 - 2023 Qore Technologies, s.r.o.

  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation
  the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.

  Note that the Qore library is released under a choice of three open-source
  licenses: MIT (as above), LGPL 2+, or GPL 2+; see README-LICENSE for more
  information.
*/

#include "qore/Qore.h"
#include "qore/InputStream.h"
#include "qore/intern/InputStreamLineIterator.h"
#include "qore/intern/QoreObjectIntern.h"
#include "qore/intern/QoreClassIntern.h"
#include "qore/intern/StreamReader.h"

//! This class defines a line iterator for input streams.
/** @since %Qore 0.8.13

    @par Example: InputStreamLineIterator basic usage
    @code{.py}
FileInputStream fis("log.txt");
InputStreamLineIterator it(fis, "\n");
while (it.next()) {
    printf("line %d = %n\n", it.index(), it.getLine());
}
    @endcode

    @see @ref Qore::DataLineIterator
    @see @ref Qore::FileLineIterator
 */
qclass InputStreamLineIterator [arg=InputStreamLineIterator* isli; ns=Qore; vparent=AbstractLineIterator; internal_members=InputStream is,StreamReader sr];

//! Creates a buffered InputStreamLineIterator object for iterating over the given \c InputStream
/** @param is the \c InputStream to iterate over
    @param encoding character encoding of the data from input stream; if not ASCII-compatible, all data will be
    converted to UTF-8; if not present, the @ref default_encoding "default character encoding" is assumed
    @param eol the optional end of line character(s) to use to detect lines in the data; if this string is not passed,
    then if the character-encoding is ASCII-compatible, the end of line character(s) are detected automatically from
    \c "\n", \c "\r", or \c "\r\n"; if the stream uses a non-ASCII-compatible character encoding, then \c "\n" is
    assumed
    @param trim if @ref True the string return values for the lines iterated will be trimmed of the eol bytes
    @param bufsize the size of the buffer for the internal @ref Qore::BufferedStreamReader "BufferedStreamReader" in
    bytes; must be a positive integer

    @throw STREAM-BUFFER-ERROR an invalid stream buffer size was specified; the buffer size must be a positive integer
    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the eol argument has a different
    @ref character_encoding "character encoding" from the data's and an error occurs during encoding conversion

    @note this variant of the InputStreamLineIterator::constructor creates a
    @ref Qore::BufferedStreamReader "BufferedStreamReader" to read the input data
 */
InputStreamLineIterator::constructor(Qore::InputStream[InputStream] is, *string encoding, *string eol,
        bool trim = True, int bufsize = DefaultStreamBufferSize) {
    if (eol && eol->empty())
        eol = nullptr;
    SimpleRefHolder<InputStreamLineIterator> li(new InputStreamLineIterator(xsink, is,
        encoding ? QEM.findCreate(encoding) : QCS_DEFAULT, eol, trim, bufsize));
    if (*xsink)
        return;
    self->setPrivate(CID_INPUTSTREAMLINEITERATOR, li.release());
    qore_object_private* o = qore_object_private::get(*self);
    const qore_class_private* cls = qore_class_private::get(*QC_INPUTSTREAMLINEITERATOR);
    o->setValueIntern(cls, "is", static_cast<QoreObject *>(obj_is->refSelf()), xsink);
}

//! Creates the InputStreamLineIterator for iterating data from the given \c StreamReader.
/** @param sr the \c StreamReader used as a source of data to iterate over
    @param eol the optional end of line character(s) to use to detect lines in the data; if this string is not passed,
    then if the character-encoding is ASCII-compatible, the end of line character(s) are detected automatically from
    \c "\n", \c "\r", or \c "\r\n"; if the stream uses a non-ASCII-compatible character encoding, then \c "\n" is
    assumed
    @param trim if @ref True the string return values for the lines iterated will be trimmed of the eol bytes

    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the eol argument has a different
    @ref character_encoding "character encoding" from the data's and an error occurs during encoding conversion
 */
InputStreamLineIterator::constructor(Qore::StreamReader[StreamReader] sr, *string eol, bool trim = True) {
    if (eol && eol->empty())
        eol = nullptr;
    SimpleRefHolder<InputStreamLineIterator> li(new InputStreamLineIterator(xsink, sr, eol, trim));
    if (*xsink)
        return;
    self->setPrivate(CID_INPUTSTREAMLINEITERATOR, li.release());
    qore_object_private* o = qore_object_private::get(*self);
    const qore_class_private* cls = qore_class_private::get(*QC_INPUTSTREAMLINEITERATOR);
    o->setValueIntern(cls, "sr", static_cast<QoreObject *>(obj_sr->refSelf()), xsink);
}

//! Moves the current position to the next line in the data; returns @ref False if there are no more lines to read; if the iterator is not pointing at a valid element before this call, the iterator will be positioned to the beginning of the data.
/** The iterator object should not be used after this method returns @ref False.

    @return @ref False if there are no more lines in the data (in which case the iterator object is invalid and should not be used); @ref True if successful (meaning that the iterator object is valid)

    @par Example:
    @code{.py}
while (i.next()) {
    printf("line: %y\n", i.getValue());
}
    @endcode

    @throw ITERATOR-THREAD-ERROR this exception is thrown if this method is called from any thread other than the thread that created the object
 */
bool InputStreamLineIterator::next() {
    if (isli->check(xsink))
        return false;
    return isli->next(xsink);
}

//! Returns the current line in the data or throws an \c ITERATOR-ERROR exception if the iterator is invalid.
/** @return the current line in the data or throws an \c ITERATOR-ERROR exception if the iterator is invalid

    @par Example:
    @code{.py}
while (i.next()) {
    printf("+ %y\n", i.getValue());
}
    @endcode

    @throw ITERATOR-ERROR the iterator is not pointing at a valid element
    @throw ITERATOR-THREAD-ERROR this exception is thrown if this method is called from any thread other than the thread that created the object

    @see InputStreamLineIterator::getLine()
 */
string InputStreamLineIterator::getValue() [flags=RET_VALUE_ONLY] {
    return isli->checkValid(xsink) ? nullptr : isli->getValue();
}

//! Returns the current line in the data or throws an \c ITERATOR-ERROR exception if the iterator is invalid.
/** @return the current line in the data or throws an \c ITERATOR-ERROR exception if the iterator is invalid

    @par Example:
    @code{.py}
while (i.next()) {
    printf("+ %y\n", i.getLine());
}
    @endcode

    @throw ITERATOR-ERROR the iterator is not pointing at a valid element
    @throw ITERATOR-THREAD-ERROR this exception is thrown if this method is called from any thread other than the thread that created the object

    @see InputStreamLineIterator::getValue()
 */
string InputStreamLineIterator::getLine() [flags=RET_VALUE_ONLY] {
    return isli->checkValid(xsink) ? nullptr : isli->getValue();
}

//! Returns @ref True if the iterator is currently pointing at a valid element, @ref False if not.
/** @return @ref True if the iterator is currently pointing at a valid element, @ref False if not

    @par Example:
    @code{.py}
if (i.valid())
    printf("current value: %y\n", i.getValue());
    @endcode
 */
bool InputStreamLineIterator::valid() [flags=CONSTANT] {
    return isli->valid();
}

//! Returns the current iterator line number in the data (the first line is line 1) or 0 if not pointing at a valid element.
/** @return the current iterator line number in the data (the first line is line 1) or 0 if not pointing at a valid element

    @par Example:
    @code{.py}
while (i.next()) {
    printf("+ %d: %y\n", i.index(), i.getValue());
}
    @endcode
 */
int InputStreamLineIterator::index() [flags=CONSTANT] {
    return isli->index();
}

//! Returns the @ref StreamReader object used internally
/** @par Example:
    @code{.py}
StreamReader sr = i.getStreamReader();
    @endcode

    @return the @ref StreamReader object used internally
 */
StreamReader InputStreamLineIterator::getStreamReader() {
    StreamReader* sr = isli->getStreamReader();
    sr->ref();
    return new QoreObject(QC_STREAMREADER, getProgram(), sr);
}

//! Returns the @ref character_encoding "character encoding" for the @ref InputStreamLineIterator
/** @par Example:
    @code{.py}
string encoding = i.getEncoding();
    @endcode

    @return the @ref character_encoding "character encoding" for the @ref InputStreamLineIterator
 */
string InputStreamLineIterator::getEncoding() [flags=CONSTANT] {
    return new QoreStringNode(isli->getEncoding());
}
