/* -*- mode: c++; indent-tabs-mode: nil -*- */
/** @file QC_ListHashIterator.qpp ListHashIterator 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/QoreListHashIterator.h"

extern QoreClass* QC_LISTHASHITERATOR;

// internal reverse iterator class implementation only for the getName() function - the iterators remain
// forwards and are used in the reverse sense by the Qore language class implementation below
class QoreListHashReverseIterator : public QoreListHashIterator {
public:
   DLLLOCAL QoreListHashReverseIterator(const QoreListNode* n_l) : QoreListHashIterator(n_l) {
   }

   DLLLOCAL QoreListHashReverseIterator(const QoreListHashReverseIterator& old) : QoreListHashIterator(old) {
   }

   DLLLOCAL virtual const char* getName() const {
      return "ListHashReverseIterator";
   }
};

//! This class a reverse iterator class for lists of hashes as returned by Qore::SQL::Datasource::selectRows() and Qore::SQL::DatasourcePool::selectRows(), both of which return hashes with keys giving column names where the key values are lists of column values
/** Call ListHashReverseIterator::next() to iterate through the lists of column values assigned to each hash key in reverse order; do not use the iterator if ListHashReverseIterator::next() returns @ref False.
    A result list can be iterated in reverse order by calling ListHashReverseIterator::prev() instead of ListHashReverseIterator::next()

    @par Example: ListHashReverseIterator basic usage
    @code{.py}
    list<auto> data = (
             ( "column1" : 1, "column2" : "a"),
             ( "column1" : 2, "column2" : "b"),
        );

    ListHashReverseIterator it(data);
    while (it.next()) {
        printf("iter %d: %n\n", it.index(), it.getValue());
    }

    iter 1: hash: (column1 : 2, column2 : "b")
    iter 0: hash: (column1 : 1, column2 : "a")
    @endcode

    @note
    - In general, the ListHashReverseIterator 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.
    - ListHashReverseIterator is functionally equivalent to ListHashIterator, but the effect of ListHashReverseIterator::next() and ListHashReverseIterator::prev()
      are the opposite of ListHashIterator::next() and ListHashIterator::prev(); that is ListHashReverseIterator::next() will
      iterate through the hash in reverse order, while ListHashReverseIterator::prev() iterates in forward order.
      Additionally the meanings of the return values for ListHashReverseIterator::first() and ListHashReverseIterator::last()
      are swapped in respect to ListHashIterator::first() and ListHashIterator::last().

    @see ListHashIterator
 */
qclass ListHashReverseIterator [arg=QoreListHashReverseIterator* i; ns=Qore; vparent=ListHashIterator];

//! Creates the list hash iterator object
/** @param l the list of hashes to iterate

    @par Example:
    @code{.py}
ListHashIterator i(l);
    @endcode

    @note the constructor's argument is @ref softlist_type "softlist" so that it can also accept @ref nothing
 */
ListHashReverseIterator::constructor(softlist<auto> l) {
   self->setPrivate(CID_LISTHASHREVERSEITERATOR, new QoreListHashReverseIterator(l));
}

//! Creates a copy of the ListHashReverseIterator object, iterating the same object as the original and in the same position
/** @par Example:
    @code{.py}
ListHashReverseIterator ni = i.copy();
    @endcode
 */
ListHashReverseIterator::copy() {
   self->setPrivate(CID_LISTHASHREVERSEITERATOR, new QoreListHashReverseIterator(*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 ListHashReverseIterator::next() {
   if (i->check(xsink))
      return false;
   return i->prev();
}

//! 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 ListHashReverseIterator::prev() {
   if (i->check(xsink))
      return false;
   return i->next();
}

//! returns @ref True if on the first element being iterated (ie the last element in the list)
/** @return @ref True if on the first element being iterated (ie the last element in the list)

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

//! returns @ref True if on the last element being iterated (ie the first element in the list)
/** @return @ref True if on the last element being iterated (ie the first element in the list)

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

//! 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

    @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 or the list being iterated does not contain a hash element at the current iterator position or the given hash key does not exist

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

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