/* -*- mode: c++; indent-tabs-mode: nil -*- */
/** @file QC_TypedHash.cpp typed hash (hashdecl) 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_reflection.h"
#include "QC_TypedHash.h"
#include "QC_TypedHashMember.h"
#include "QC_Class.h"
#include "QC_Type.h"
#include "QC_Namespace.h"
#include "QC_Constant.h"
#include "QC_Function.h"
#include "QC_GlobalVar.h"
#include "QC_TypedHash.h"
#include "QC_FunctionVariant.h"

QoreReflectionTypedHash::QoreReflectionTypedHash(ExceptionSink* xsink, const char* path, QoreProgram* pgm)
    : AbstractReflectionObject(pgm) {
    th = pgm->findHashDecl(path, ns);

    if (!th) {
        xsink->raiseException("UNKNOWN-TYPED-HASH", "cannot resolve typed hash (hashdecl) '%s'", path);
        return;
    }
}

static QoreValue find_all_typedhashes(const QoreString& pattern, int re_opts, QoreProgram* pgm, ExceptionSink* xsink) {
    hashdecl_vec_t hashdecl_vec = pgm->findAllHashDeclsRegex(pattern, re_opts, xsink);
    if (*xsink) {
        return QoreValue();
    }

    ReferenceHolder<QoreListNode> l(new QoreListNode(QC_TYPEDHASH->getTypeInfo()), xsink);
    for (auto& i : hashdecl_vec) {
        l->push(new QoreObject(QC_TYPEDHASH, pgm, new QoreReflectionTypedHash(pgm, i.first, i.second)), xsink);
    }

    return l.release();
}

//! The base class for %Qore typed hashes (@ref hashdecl "hashdecls")
/**
    @since %Qore 0.9.0
 */
qclass TypedHash [ns=Qore::Reflection; arg=QoreReflectionTypedHash* thd; dom=REFLECTION];

//! Creates the object from the @ref hashdecl "typed hash (hashdecl)" name or namespace-justified path as a string
/** @par Example:
    @code{.py}
TypedHash th("::ARGV");
    @endcode

    @param path the @ref hashdecl "typed hash (hashdecl)" name or namespace-justified path as a string

    @throw UNKNOWN-TYPED-HASH cannot find a @ref hashdecl "typed hash (hashdecl)" with the given name or path
    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the string argument is not in the @ref default_encoding "default character encoding" and an error occurs during encoding conversion

    @see forName()
 */
TypedHash::constructor(string path) {
    TempEncodingHelper npath(path, QCS_DEFAULT, xsink);
    if (*xsink) {
        return;
    }

    ReferenceHolder<QoreReflectionTypedHash> th(new QoreReflectionTypedHash(xsink, npath->c_str()), xsink);
    if (*xsink) {
        return;
    }
    self->setPrivate(CID_TYPEDHASH, th.release());
}

//! Returns @ref True if the typed hash passed as an argument is equal to the current object; @ref False if not
/** @par Example:
    @code{.py}
bool b = th1.isEqual(th2);
    @endcode

    @param th the @ref hashdecl "typed hash (hashdecl)" to check with the current object for equality

    @return @ref True if the object passed as an argument is equal to the current object; @ref False if not

    @note if this method is called on user typed hashes (hashdecls) created from the same source code but in different
    @ref Qore::Program "Program" containers, it will return @ref False
*/
bool TypedHash::isEqual(TypedHash[QoreReflectionTypedHash] th) [flags=CONSTANT] {
    ReferenceHolder<QoreReflectionTypedHash> holder(th, xsink);

    return thd->th == th->th;
}

//! returns the @ref hashdecl "typed hash (hashdecl)" name
/** @par Example:
    @code{.py}
string name = th.getName();
    @endcode

    @return the @ref hashdecl "typed hash (hashdecl)" name

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed

    @see getPathName()
 */
string TypedHash::getName() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash (hashdecl) ptr must be valid
    return new QoreStringNode(thd->th->getName());
}

//! returns the @ref hashdecl "typed hash's (hashdecl's)" full namespace-justified path name
/** @par Example:
    @code{.py}
string name = th.getPathName();
    @endcode

    @return the @ref hashdecl "typed hash's (hashdecl's)" full namespace-justified path name

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed

    @see getName()
 */
string TypedHash::getPathName() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash (hashdecl) ptr must be valid
    SimpleRefHolder<QoreStringNode> rv(new QoreStringNode);
    rv->concat(thd->th->getNamespacePath());
    return rv.release();
}

//! Returns the module name providing the typed hash or @ref nothing if the typed hash was not provided by a module
/** @par Example:
    @code{.py}
*string str = th.getModuleName();
    @endcode

    @return the module name providing the typed hash or @ref nothing if the typed hash was not provided by a module
*/
*string TypedHash::getModuleName() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the class ptr must be valid
    const char* mod = thd->th->getModuleName();
    return mod ? new QoreStringNode(mod) : QoreValue();
}

//! returns @ref True if the @ref hashdecl "typed hash (hashdecl)" is a builtin typed hash
/** @par Example:
    @code{.py}
bool b = th.isBuiltin();
    @endcode

    @return @ref True if the @ref hashdecl "typed hash (hashdecl)" is a builtin typed hash

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed

    @note complementary to @ref isUser()
*/
bool TypedHash::isBuiltin() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash (hashdecl) ptr must be valid
    return thd->th->isSystem();
}

//! returns @ref True if the @ref hashdecl "typed hash (hashdecl)" is a user typed hash
/** @par Example:
    @code{.py}
bool b = th.isUser();
    @endcode

    @return @ref True if the @ref hashdecl "typed hash (hashdecl)" is a user typed hash

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed

    @note complementary to @ref isBuiltin()
*/
bool TypedHash::isUser() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash (hashdecl) ptr must be valid
    return !thd->th->isSystem();
}

//! Returns the source location of the @ref hashdecl "typed hash (hashdecl)" declaration
/** @par Example:
    @code{.py}
hash<SourceLocationInfo> loc = th.getSourceLocation();
    @endcode

    @return the source location of the @ref hashdecl "typed hash (hashdecl)" declaration

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed
*/
hash<SourceLocationInfo> TypedHash::getSourceLocation() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash ptr must be valid
    return thd->th->getSourceLocation()->getHash();
}

//! Returns the type object for this typed hash
/** @par Example:
    @code{.py}
Type t = th.getType();
    @endcode

    @return the type object for this typed hash

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed

    @see getOrNothingType()
*/
Type TypedHash::getType() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash ptr must be valid
    return new QoreObject(QC_TYPE, thd->pgm, new QoreType(thd->th->getTypeInfo()));
}

//! Returns the "or nothing" type object for this typed hash
/** @par Example:
    @code{.py}
Type t = th.getOrNothingType();
    @endcode

    @return the "or nothing" type object for this typed hash

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the typed hash has been destroyed

    @see getType()
*/
Type TypedHash::getOrNothingType() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash ptr must be valid
    return new QoreObject(QC_TYPE, thd->pgm, new QoreType(thd->th->getTypeInfo(true)));
}

//! Returns the namespace for the typed hash
/** @par Example:
    @code{.py}
Namespace ns = th.getNamespace();
    @endcode

    @return the namespace for the typed hash
 */
Namespace TypedHash::getNamespace() [flags=CONSTANT] {
    return new QoreObject(QC_NAMESPACE, thd->pgm, new QoreReflectionNamespace(thd->pgm, thd->ns));
}

//! returns the requested member or throws an exception if the member is not defined in the @ref hashdecl "typed hash (hashdecl)"
/**  @par Example:
    @code{.py}
TypedHashMember m = th.getMember(name);
    @endcode

    @return the requested member or throws an exception if the member is not defined in the @ref hashdecl "typed hash (hashdecl)"

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the @ref hashdecl "typed hash (hashdecl)" has been destroyed
    @throw UNKNOWN-MEMBER if the requested member is not defined in the @ref hashdecl "typed hash (hashdecl)"
    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the string argument is not in the @ref default_encoding "default character encoding" and an error occurs during encoding conversion
*/
TypedHashMember TypedHash::getMember(string name) [flags=RET_VALUE_ONLY] {
    TempEncodingHelper tname(name, QCS_DEFAULT, xsink);
    if (*xsink) {
        return QoreValue();
    }

    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash ptr must be valid
    const QoreExternalMemberBase* mi = thd->th->findLocalMember(tname->c_str());
    if (!mi) {
        xsink->raiseException("UNKNOWN-MEMBER", "member '%s' is not defined in typed hash (hashdecl) '%s'", tname->c_str(), thd->th->getName());
        return QoreValue();
    }

    return new QoreObject(QC_TYPEDHASHMEMBER, thd->pgm, new QoreReflectionHashDeclMember(thd->pgm, thd->th, tname->c_str(), mi));
}

//! returns a list of all declared @ref hashdecl "typed hash (hashdecl)" members in declaration order
/** @par Example:
    @code{.py}
list<TypedHashMember> l = th.getMembers();
    @endcode

    @return a list of all declared @ref hashdecl "typed hash (hashdecl)" members in declaration order

    @throw PROGRAM-ERROR thrown if the @ref Qore::Program "Program" object holding the class has been destroyed
*/
list<TypedHashMember> TypedHash::getMembers() [flags=RET_VALUE_ONLY] {
    // get read access to program object
    QoreExternalProgramContextHelper tch(xsink, thd->pgm);
    if (*xsink) {
        return QoreValue();
    }

    // the typed hash ptr must be valid
    ReferenceHolder<QoreListNode> l(new QoreListNode(QC_TYPEDHASHMEMBER->getTypeInfo()), xsink);

    TypedHashDeclMemberIterator i(*thd->th);
    while (i.next()) {
        l->push(new QoreObject(QC_TYPEDHASHMEMBER, thd->pgm, new QoreReflectionHashDeclMember(thd->pgm, thd->th, i.getName(), &i.getMember())), xsink);
    }

    return l.release();
}

//! Returns a typed hash for the given hash, if possible
/** @param h the hash to convert

    @throw RUNTIME-TYPE-ERROR types are not compatible

    @since %Qore 0.9.5
*/
hash<auto> TypedHash::doCast(hash<auto> h) {
    return thd->th->doRuntimeCast(h, xsink);
}

//! Returns a @ref hashdecl "typed hash (hashdecl)" object corresponding to the name or namespace-justified path provided as an argument
/** @par Example:
    @code{.py}
TypedHash th = TypedHash::forName("::ENV");
    @endcode

    @param path the @ref hashdecl "typed hash (hashdecl)" name or namespace-justified path as a string

    @return a @ref hashdecl "typed hash (hashdecl)" object corresponding to the name or namespace-justified path provided as an argument

    @throw UNKNOWN-TYPED-HASH cannot find a @ref hashdecl "typed hash (hashdecl)" with the given name or path
    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the string argument is not in the @ref default_encoding "default character encoding" and an error occurs during encoding conversion
 */
static TypedHash TypedHash::forName(string path) [flags=RET_VALUE_ONLY] {
    TempEncodingHelper npath(path, QCS_DEFAULT, xsink);
    if (*xsink) {
        return QoreValue();
    }

    ReferenceHolder<QoreReflectionTypedHash> th(new QoreReflectionTypedHash(xsink, npath->c_str()), xsink);
    if (*xsink) {
        return QoreValue();
    }
    assert(*th);

    QoreProgram* hash_pgm = th->pgm;
    return new QoreObject(QC_TYPEDHASH, hash_pgm, th.release());
}

//! Returns a @ref hashdecl "typed hash (hashdecl)" object corresponding to the name or namespace-justified path provided as an argument
/** @par Example:
    @code{.py}
TypedHash th = TypedHash::forName(pgm, "::ENV");
    @endcode

    @param pgm the Program object to search
    @param path the @ref hashdecl "typed hash (hashdecl)" name or namespace-justified path as a string

    @return a @ref hashdecl "typed hash (hashdecl)" object corresponding to the name or namespace-justified path provided as an argument

    @throw UNKNOWN-TYPED-HASH cannot find a @ref hashdecl "typed hash (hashdecl)" with the given name or path
    @throw ENCODING-CONVERSION-ERROR this exception could be thrown if the string argument is not in the @ref default_encoding "default character encoding" and an error occurs during encoding conversion
 */
static TypedHash TypedHash::forName(Program[QoreProgram] pgm, string path) [flags=RET_VALUE_ONLY] {
    ReferenceHolder<QoreProgram> pgm_holder(pgm, xsink);
    TempEncodingHelper npath(path, QCS_DEFAULT, xsink);
    if (*xsink) {
        return QoreValue();
    }

    ReferenceHolder<QoreReflectionTypedHash> th(new QoreReflectionTypedHash(xsink, npath->c_str(), pgm), xsink);
    if (*xsink) {
        return QoreValue();
    }

    QoreProgram* hash_pgm = th->pgm;
    return new QoreObject(QC_TYPEDHASH, hash_pgm, th.release());
}

//! Returns a list of typed hashes (hashdecls) matching the regular expression pattern argument or an empty list if no typed hashes match
/** @par Example:
    @code{.py}
# return all accessible typed hashes (hashdecls) that start with the letter "S"
list<TypedHash> l = TypedHash::findAllRegex("^S");
    @endcode

    @param pattern the regular expression pattern to match
    @param re_opts see @ref regex_constants for possible values

    @return a list of typed hashes (hashdecls) matching the regular expression pattern argument or an empty list if no typed hashes match
*/
static list<TypedHash> TypedHash::findAllRegex(string pattern, *int re_opts) [flags=RET_VALUE_ONLY] {
    return find_all_typedhashes(*pattern, re_opts, getProgram(), xsink);
}

//! Returns a list of typed hashes (hashdecls) matching the regular expression pattern argument or an empty list if no typed hashes match
/** @par Example:
    @code{.py}
# return all accessible typed hashes (hashdecls) that start with the letter "S"
list<TypedHash> l = TypedHash::findAllRegex(pgm, "^S");
    @endcode

    @param pgm the Program object to search
    @param pattern the regular expression pattern to match
    @param re_opts see @ref regex_constants for possible values

    @return a list of typed hashes (hashdecls) matching the regular expression pattern argument or an empty list if no typed hashes match
*/
static list<TypedHash> TypedHash::findAllRegex(Program[QoreProgram] pgm, string pattern, *int re_opts) [flags=RET_VALUE_ONLY] {
    ReferenceHolder<QoreProgram> pgm_holder(pgm, xsink);
    return find_all_typedhashes(*pattern, re_opts, pgm, xsink);
}
