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

    Copyright (C) 2003 - 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 <cerrno>

#include "qore/Qore.h"
#include "qore/intern/FileLineIterator.h"
#include "qore/intern/qore_qf_private.h"

//! This class defines a line iterator for text files
/** @since %Qore 0.8.6

    @par Example: FileLineIterator basic usage
    @code{.py}
    file content:
    a2ps-4.13-1332.1.x86_64
    a2ps-devel-4.13-1332.1.x86_64
    aaa_base-11.3-7.2.x86_64
    ...

    FileLineIterator it("/export/home/pvanek/ren.list");
    while (it.next()) {
        printf("%s:%d = %n\n", it.getFileName(), it.index(), it.getValue());
    }

    /export/home/pvanek/ren.list:1 = "a2ps-4.13-1332.1.x86_64"
    /export/home/pvanek/ren.list:2 = "a2ps-devel-4.13-1332.1.x86_64"
    /export/home/pvanek/ren.list:3 = "aaa_base-11.3-7.2.x86_64"
    ...
    /export/home/pvanek/ren.list:2155 = "zypper-1.4.5-1.10.x86_64"
    @endcode

    @see @ref Qore::InputStreamLineIterator
    @see @ref Qore::DataLineIterator
 */
qclass FileLineIterator [arg=FileLineIterator* i; ns=Qore; vparent=AbstractLineIterator; dom=FILESYSTEM];

//! Opens the given file for reading with the given options and creates the FileLineIterator object
/** @param path the path to open for reading
    @param encoding character encoding of the data in the file; 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 file; if this string is not passed, then the end of line character(s) are detected automatically, and can be either \c "\n", \c "\r", or \c "\r\n" (the last one is only automatically detected when not connected to a terminal device in order to keep the I/O from stalling); if this string is passed and has a different @ref character_encoding "character encoding" from this object's (as determined by the \c encoding parameter), then it will be converted to the FileLineIterator's @ref character_encoding "character encoding"
    @param trim if @ref True the string return values for the lines iterated will be trimmed of the eol bytes
    @param nonblocking_open if @ref True, then the \c O_NONBLOCK flag will be set in the call to <tt>open() (2)</tt>

    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the eol argument has a different @ref character_encoding "character encoding" from the File's and an error occurs during encoding conversion
    @throw ILLEGAL-EXPRESSION FileLineIterator::constructor() cannot be called with a TTY target when @ref no-terminal-io "%no-terminal-io" is set

    @since %Qore 0.9.3 added the \a nonblocking_open flag
 */
FileLineIterator::constructor(string path, *string encoding, *string eol, bool trim = True, *bool nonblocking_open) {
    if (eol && eol->empty())
        eol = 0;
    int flags = nonblocking_open ? O_NONBLOCK : 0;

    SimpleRefHolder<FileLineIterator> fli(new FileLineIterator(xsink, path, encoding ? QEM.findCreate(encoding) : QCS_DEFAULT, eol, trim, flags));
    if (*xsink)
        return;

    if (fli->isTty() && runtime_check_parse_option(PO_NO_TERMINAL_IO)) {
        xsink->raiseException("ILLEGAL-EXPRESSION", "FileLineIterator::constructor() cannot be called with a TTY target when 'no-terminal-io' is set");
        return;
    }

    self->setPrivate(CID_FILELINEITERATOR, fli.release());
}

//! Creates a new FileLineIterator object, based on the same object being iterated in the original object (the original file is reopened)
/** @par Example:
    @code{.py}
FileLineIterator ni = i.copy();
    @endcode

    @throw ILLEGAL-EXPRESSION FileLineIterator::constructor() cannot be called with a TTY target when @ref no-terminal-io "%no-terminal-io" is set
 */
FileLineIterator::copy() {
    SimpleRefHolder<FileLineIterator> fli(new FileLineIterator(xsink, *i));

    if (fli->isTty() && runtime_check_parse_option(PO_NO_TERMINAL_IO)) {
        xsink->raiseException("ILLEGAL-EXPRESSION", "FileLineIterator::copy() cannot be called with a TTY target when 'no-terminal-io' is set");
        return;
    }

    if (!*xsink)
        self->setPrivate(CID_FILELINEITERATOR, fli.release());
}

//! Moves the current position to the next line in the file; 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 file
/** This method will return @ref True again after it returns @ref False once if file is not empty, otherwise it will always return @ref False
    The iterator object should not be used after this method returns @ref False

    @return @ref False if there are no more lines in the file (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 FileLineIterator::next() {
    if (i->check(xsink))
        return false;
    return i->next(xsink);
}

//! Returns the current line in the file or throws an \c ITERATOR-ERROR exception if the iterator is invalid
/** @return the current line in the file 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 FileLineIterator::getLine()
 */
string FileLineIterator::getValue() [flags=RET_VALUE_ONLY] {
    return i->checkValid(xsink) ? 0 : i->getValue();
}

//! Returns the current line in the file or throws an \c ITERATOR-ERROR exception if the iterator is invalid
/** @return the current line in the file 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 FileLineIterator::getValue()
 */
string FileLineIterator::getLine() [flags=RET_VALUE_ONLY] {
    return i->checkValid(xsink) ? 0 : i->getValue();
}

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

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

//! Returns the current iterator line number in the file (the first line is line 1) or 0 if not pointing at a valid element
/** @return the current iterator line number in the file (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 FileLineIterator::index() [flags=CONSTANT] {
    return i->index();
}

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

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

//! Returns @ref True "True" if the FileLineIterator is connected to a terminal device, @ref False "False" if not
/** @return @ref True "True" if the FileLineIterator is connected to a terminal device, @ref False "False" if not

    @par Example:
    @code{.py}
bool b = i.isTty();
    @endcode
*/
bool FileLineIterator::isTty() [flags=CONSTANT] {
    return i->isTty();
}

//! Returns the file path/name used to open the file
/** @par Example:
    @code{.py}
string fn = f.getFileName();
    @endcode

    @return the file path/name used to open the file
 */
string FileLineIterator::getFileName() [flags=CONSTANT] {
    return i->getFileName()->stringRefSelf();
}

//! Returns @ref stat_list of stat() of the underlying file
/** If any errors occur, a \c FILE-HSTAT-ERROR exception is thrown
    @par Example:
    @code{.py}
list<auto> l = f.stat();
    @endcode

    @return @ref stat_list of stat() of the underlying file
    @since %Qore 0.8.12
 */
list<auto> FileLineIterator::stat() [flags=CONSTANT] {
    return i->stat(xsink);
}

//! Returns @ref StatInfo "StatInfo" hash of hstat() of the underlying file
/** If any errors occur, a \c FILE-HSTAT-ERROR exception is thrown
    @par Example:
    @code{.py}
hash<StatInfo> h = f.hstat();
    @endcode

    @return @ref StatInfo "StatInfo" hash of hstat() of the underlying file

    @since %Qore 0.8.12
 */
hash<StatInfo> FileLineIterator::hstat() [flags=CONSTANT] {
    return i->hstat(xsink);
}

//! Reset the iterator instance to its initial state
/** Reset the iterator instance to its initial state

   @par Example
   @code{.py}
i.reset();
   @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
 */
FileLineIterator::reset() {
    if (!i->check(xsink))
        i->reset(xsink);
}
