/* -*- mode: c++; indent-tabs-mode: nil -*- */
/** @file QC_HashListIterator.qpp HashListIterator 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 <qore/Qore.h>
#include "qore/intern/QoreHashListIterator.h"

//! This class an iterator class for hashes of lists as returned by Qore::SQL::Datasource::select() and Qore::SQL::DatasourcePool::select(), both of which return hashes with keys giving column names where the key values are lists of column values
/** This class can be used as a more flexible alternative to the @ref context "context statement".

    Call HashListIterator::next() to iterate through the lists of column values assigned to each hash key; do not use the iterator if HashListIterator::next() returns @ref False.
    A result list can be iterated in reverse order by calling HashListIterator::prev() instead of HashListIterator::next()

    @par Example: HashListIterator basic usge
    @code{.py}
    hash<auto> data = {
        "column1": (1, 2, 3,),
        "column2": ("a", "b", "c",),
        "column3": "constant",
    };

    HashListIterator it(data);
    while (it.next()) {
        printf("iter %d: getValue: %y; getKeyValue('column1'): %y\n",
               it.index(), it.getValue(), it.getKeyValue('column1'));
    }

    iter 0: getValue: {column1: 1, column2: "a", column3: "constant"}; getKeyValue('column1'): 1
    iter 1: getValue: {column1: 2, column2: "b", column3: "constant"}; getKeyValue('column1'): 2
    iter 2: getValue: {column1: 3, column2: "c", column3: "constant"}; getKeyValue('column1'): 3
    @endcode

    @note
    - A hash with all non-list values will be iterated as if each key value were a single element list
    - A hash with mixed lists and single values will have the single values used as the repeating value for every element in the list (as in the above example), however all lists must be of the same size or a runtime exception will be raised
    - A hash with empty lists and constants will not be iterated; in this case the constant values will be ignored; values with lists determine the number of times the data structure will be iterated
    - In general, the HashListIterator class is not designed to be accessed from multiple threads; it was created without locking for
      fast and efficient use when used from a single thread.  For methods that would be unsafe to use in another thread, any use of
      such methods in threads other than the thread where the constructor was called will cause an \c ITERATOR-THREAD-ERROR to be thrown.

    @see HashListReverseIterator
 */
qclass HashListIterator [arg=QoreHashListIterator* i; ns=Qore; vparent=AbstractQuantifiedBidirectionalIterator];

//! Creates the hash list iterator object
/** @param h the hash of lists to iterate

    @par Example:
    @code{.py}
HashListIterator i(h);
    @endcode

    @note a hash with non-list values will be iterated as if each key value were a single element list
 */
HashListIterator::constructor(hash<auto> h) {
   self->setPrivate(CID_HASHLISTITERATOR, new QoreHashListIterator(h));
}

//! Creates an empty hash list iterator object
/** @par Example:
    @code{.py}
*hash<auto> q = ds.select("select * from some_table");
HashListIterator i(q);
    @endcode
 */
HashListIterator::constructor() {
   self->setPrivate(CID_HASHLISTITERATOR, new QoreHashListIterator);
}

//! Creates a copy of the HashListIterator object, iterating the same object as the original and in the same position
/** @par Example:
    @code{.py}
HashListIterator ni = i.copy();
    @endcode
 */
HashListIterator::copy() {
   self->setPrivate(CID_HASHLISTITERATOR, new QoreHashListIterator(*i));
}

//! Moves the current position to the next element in the result list; returns @ref False if there are no more elements; if the iterator is not pointing at a valid element before this call, the iterator will be positioned on the first element in the list if the list is not empty
/** This method will return @ref True again after it returns @ref False once if list 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 elements in the result list (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(" + row %d: %y\n", i.index(), 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 HashListIterator::next() {
   if (i->check(xsink))
      return false;
   return i->next();
}

//! Moves the current position to the previous element in the result list; returns @ref False if there are no more elements; if the iterator is not pointing at a valid element before this call, the iterator will be positioned on the last element in the list if the list is not empty
/** This method will return @ref True again after it returns @ref False once if the list 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 elements in the result list (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.prev()) {
    printf(" + row %d: %y\n", i.index(), 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 HashListIterator::prev() {
   if (i->check(xsink))
      return false;
   return i->prev();
}

//! returns @ref True if the result list is empty; @ref False if not
/** @return @ref True if the result list is empty; @ref False if not

    @par Example:
    @code{.py}
if (i.empty())
    printf("the result list is empty\n");
    @endcode
 */
bool HashListIterator::empty() [flags=CONSTANT] {
   return i->empty();
}

//! returns @ref True if on the first element of the list
/** @return @ref True if on the first element of the list

    @par Example:
    @code{.py}
while (i.next()) {
    if (i.first())
        printf("START:\n");
}
    @endcode
 */
bool HashListIterator::first() [flags=CONSTANT] {
   return i->first();
}

//! returns @ref True if on the last element of the list
/** @return @ref True if on the last element of the list

    @par Example:
    @code{.py}
while (i.next()) {
    if (i.last())
        printf("END.\n");
}
    @endcode
 */
bool HashListIterator::last() [flags=CONSTANT] {
   return i->last();
}

//! returns the current row value as a hash or throws an \c INVALID-ITERATOR exception if the iterator is invalid
/** @return the current row value as a hash or throws an \c INVALID-ITERATOR exception if the iterator is invalid; each key value in the hash returned will be equal to the current list element for the element being iterated, or, if the key value in the hash being iterated is a constant (i.e. non-list) value, then this constant value will be returned as the key value directly

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

    @note
    - equivalent to HashListIterator::getRow()

    @throw ITERATOR-THREAD-ERROR this exception is thrown if this method is called from any thread other than the thread that created the object
    @throw INVALID-ITERATOR the iterator is not pointing at a valid element
    @throw HASHLISTITERATOR-ERROR the one of the hash keys has a value that is a list with a size that does not match the expected list size
 */
hash<auto> HashListIterator::getValue() [flags=RET_VALUE_ONLY] {
   if (i->check(xsink))
      return QoreValue();
   return i->getRow(xsink);
}

//! returns the current row value as a hash or throws an \c INVALID-ITERATOR exception if the iterator is invalid
/** @return the current row value as a hash or throws an \c INVALID-ITERATOR exception if the iterator is invalid; each key value in the hash returned will be equal to the current list element for the element being iterated, or, if the key value in the hash being iterated is a constant (i.e. non-list) value, then this constant value will be returned as the key value directly

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

    @note equivalent to HashListIterator::getValue()

    @throw ITERATOR-THREAD-ERROR this exception is thrown if this method is called from any thread other than the thread that created the object
    @throw INVALID-ITERATOR the iterator is not pointing at a valid element
    @throw HASHLISTITERATOR-ERROR the one of the hash keys has a value that is a list with a size that does not match the expected list size
 */
hash<auto> HashListIterator::getRow() [flags=RET_VALUE_ONLY] {
   if (i->check(xsink))
      return QoreValue();
   return i->getRow(xsink);
}

//! returns the current iterator position in the list or -1 if not pointing at a valid element
/** @return the current iterator position in the list or -1 if not pointing at a valid element

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

//! returns the number of elements in the list
/** @return the number of elements in the list

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

//! sets the new position in the result list; if the position is invalid then the method returns @ref False, meaning the iterator is not valid, otherwise it returns @ref True
/** @param pos the new position for the iterator with 0 as the first element

    @return @ref False, meaning the iterator is not valid, otherwise it returns @ref True

    @par Example:
    @code{.py}
if (!i.set(pos))
    throw "INVALID-POSITION", sprintf("%d is an invalid position", pos);
    @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 HashListIterator::set(int pos) {
   if (i->check(xsink))
      return false;
   return !i->set(pos);
}

//! This method allows the iterator to be dereferenced directly as a hash for the current row being iterated, as memberGate methods are called implicitly when an unknown member is accessed from outside the class.
/** @param key the column name for the value to retrieve

    @return the current column value of the given row; the key value returned will be equal to the current list element for the given key, or, if the source key value is a constant (i.e. non-list) value, then this constant value will be returned directly

    @par Example:
    @code{.py}
while (i.next()) {
    printf("%d: value: %y", i.index(), i.value);
}
    @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
    @throw INVALID-ITERATOR the iterator is not pointing at a valid element
    @throw HASHLISTITERATOR-ERROR the hash key given has a value that is a list with a size that does not match the expected list size

    @note equivalent to HashListIterator::getKeyValue() when called explicitly
 */
auto HashListIterator::memberGate(string key) [flags=RET_VALUE_ONLY] {
   if (i->check(xsink))
      return QoreValue();

   return i->getReferencedKeyValue(key->getBuffer(), xsink);
}

//! Returns the current value for the column given as an argument
/** @param key the column name for the value to retrieve

    @return the current column value of the given row; the key value returned will be equal to the current list element for the given key, or, if the source key value is a constant (i.e. non-list) value, then this constant value will be returned directly

    @par Example:
    @code{.py}
while (i.next()) {
    printf("%d: value: %y", i.index(), i.getKeyValue("value"));
}
    @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
    @throw INVALID-ITERATOR the iterator is not pointing at a valid element
    @throw HASHLISTITERATOR-ERROR the hash key given has a value that is a list with a size that does not match the expected list size

    @note HashListIterator::memberGate() allows for the iterator to act as if it is a hash with members equal to the current row being iterated
 */
auto HashListIterator::getKeyValue(string key) [flags=RET_VALUE_ONLY] {
   if (i->check(xsink))
      return QoreValue();

   return i->getReferencedKeyValue(key->getBuffer(), xsink);
}

//! 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 HashListIterator::valid() [flags=CONSTANT] {
   return i->valid();
}

//! 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
 */
HashListIterator::reset() {
   if (i->check(xsink))
       return QoreValue();
   i->reset();
}
