/* -*- 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"

extern QoreClass* QC_HASHLISTITERATOR;

// 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 QoreHashListReverseIterator : public QoreHashListIterator {
public:
    DLLLOCAL QoreHashListReverseIterator(const QoreHashNode* n_h) : QoreHashListIterator(n_h) {
    }

    DLLLOCAL QoreHashListReverseIterator() {
    }

    DLLLOCAL QoreHashListReverseIterator(const QoreHashListReverseIterator& old) : QoreHashListIterator(old) {
    }

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

//! This class a reverse 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
/** Like the Qore::HashListIterator class, this class can be used as a more flexible alternative to the @ref context "context statement",
    except this class will iterate the result list in reverse order.

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

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

    HashListReverseIterator 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: 3, column2: "c", column3: "constant"}; getKeyValue('column1'): 3
    iter 1: getValue: {column1: 2, column2: "b", column3: "constant"}; getKeyValue('column1'): 2
    iter 2: getValue: {column1: 1, column2: "a", column3: "constant"}; getKeyValue('column1'): 1
    @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 HashListReverseIterator 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.
    - HashListReverseIterator is functionally equivalent to HashListIterator, but the effect of HashListReverseIterator::next() and HashListReverseIterator::prev()
      are the opposite of HashListIterator::next() and HashListIterator::prev(); that is HashListReverseIterator::next() will
      iterate through the hash in reverse order, while HashListReverseIterator::prev() iterates in forward order.
      Additionally the meanings of the return values for HashListReverseIterator::first() and HashListReverseIterator::last()
      are swapped in respect to HashListIterator::first() and HashListIterator::last().

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

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

    @par Example:
    @code{.py}
HashListReverseIterator i(h);
    @endcode
 */
HashListReverseIterator::constructor(hash<auto> h) {
    self->setPrivate(CID_HASHLISTREVERSEITERATOR, new QoreHashListReverseIterator(h));
}

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

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

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

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

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

    @par Example:
    @code{.py}
while (i.next()) {
    if (i.last())
        printf("END.\n");
}
    @endcode
 */
bool HashListReverseIterator::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; 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 HashListReverseIterator::memberGate(string key) [flags=RET_VALUE_ONLY] {
    if (i->check(xsink))
        return QoreValue();

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