/*
 * The OpenSAML License, Version 1.
 * Copyright (c) 2002
 * University Corporation for Advanced Internet Development, Inc.
 * All rights reserved
 *
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution, if any, must include
 * the following acknowledgment: "This product includes software developed by
 * the University Corporation for Advanced Internet Development
 * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
 * may appear in the software itself, if and wherever such third-party
 * acknowledgments normally appear.
 *
 * Neither the name of OpenSAML nor the names of its contributors, nor
 * Internet2, nor the University Corporation for Advanced Internet Development,
 * Inc., nor UCAID may be used to endorse or promote products derived from this
 * software without specific prior written permission. For written permission,
 * please contact opensaml@opensaml.org
 *
 * Products derived from this software may not be called OpenSAML, Internet2,
 * UCAID, or the University Corporation for Advanced Internet Development, nor
 * may OpenSAML appear in their name, without prior written permission of the
 * University Corporation for Advanced Internet Development.
 *
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
 * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
 * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


/* SAMLAttribute.cpp - abstract SAML attribute class

   Scott Cantor
   2/23/02
*/

#include "internal.h"

using namespace saml;
using namespace std;

SAMLAttribute::SAMLAttributeFactoryMap SAMLAttribute::m_map;

void SAMLAttribute::regFactory(const XMLCh* attrName, const XMLCh* attrNamespace, SAMLAttributeFactory* factory)
{
    if (attrName && attrNamespace && factory)
        m_map.insert(SAMLAttributeFactoryMap::value_type(xstring(attrName) + chBang + chBang + attrNamespace,factory));
}

void SAMLAttribute::unregFactory(const XMLCh* attrName, const XMLCh* attrNamespace)
{
    if (attrName && attrNamespace)
        m_map.erase(xstring(attrName) + chBang + chBang + attrNamespace);
    else if (!attrName && !attrNamespace)
        m_map.clear();
}

SAMLAttribute* SAMLAttribute::getInstance(DOMElement* e)
{
    if (!e)
        throw MalformedException(SAMLException::RESPONDER,"SAMLAttribute::getInstance given an empty DOM");

    const XMLCh* attrName=e->getAttributeNS(NULL,L(AttributeName));
    const XMLCh* attrNamespace=e->getAttributeNS(NULL,L(AttributeNamespace));

    if (!attrName || !attrNamespace)
        throw MalformedException(SAMLException::RESPONDER,"SAMLAttribute::getInstance can't find AttributeName or Namespace on root element");

    SAMLAttribute* a=NULL;
    SAMLConfig::getConfig().saml_lock();
    SAMLAttributeFactoryMap::const_iterator i=m_map.find(xstring(attrName) + chBang + chBang + attrNamespace);
    SAMLAttributeFactory* f=(i!=m_map.end()) ? i->second : NULL;
    SAMLConfig::getConfig().saml_unlock();
    if (f)
    {
        a=f(e);
    }
    else
    {
        auto_ptr<char> name(XMLString::transcode(attrName));
        saml::NDC ndc("getInstance");
        Category::getInstance(SAML_LOGCAT".SAMLAttribute").warn("using default attribute implementation for %s",name.get());
        a=new SAMLAttribute(e);
    }
    a->addValues(e);
    return a;
}

SAMLAttribute* SAMLAttribute::getInstance(istream& in)
{
    XML::Parser p;
    XML::StreamInputSource src(in);
    Wrapper4InputSource dsrc(&src,false);
    DOMDocument* doc=p.parse(dsrc);
    try
    {
        SAMLAttribute* a=getInstance(doc->getDocumentElement());
        a->setDocument(doc);
        return a;
    }
    catch(...)
    {
        doc->release();
        throw;
    }
}

SAMLAttribute::SAMLAttribute(const XMLCh* name, const XMLCh* ns, const saml::QName* type, long lifetime,
                             const Iterator<const XMLCh*>& values)
{
    RTTI(SAMLAttribute);
    if (!name || !*name || !ns || !*ns)
        throw MalformedException(SAMLException::RESPONDER,"SAMLAttribute() requires attribute name and namespace");
    m_name=XMLString::replicate(name);
    m_namespace=XMLString::replicate(ns);
    m_type=type ? new saml::QName(*type) : NULL;
    m_lifetime=lifetime;
    while (values.hasNext())
        m_values.push_back(values.next());
}

SAMLAttribute::SAMLAttribute(DOMElement* e) : m_name(NULL), m_namespace(NULL), m_type(NULL)
{
    RTTI(SAMLAttribute);
    fromDOM(e);
}

SAMLAttribute::SAMLAttribute(istream& in) : SAMLObject(in), m_name(NULL), m_namespace(NULL), m_type(NULL)
{
    RTTI(SAMLAttribute);
    fromDOM(m_document->getDocumentElement());
}

void SAMLAttribute::addValues(DOMElement* e)
{
    DOMNodeList* nlist=e->getElementsByTagNameNS(XML::SAML_NS,L(AttributeValue));
    for (int i=0; nlist && i<nlist->getLength(); i++)
    {
        if (!m_type)
            m_type=saml::QName::getQNameAttribute(static_cast<DOMElement*>(nlist->item(0)),XML::XSI_NS,L(type));
        addValue(static_cast<DOMElement*>(nlist->item(i)));
    }
}

SAMLAttribute::~SAMLAttribute()
{
    if (m_bOwnStrings)
    {
        delete[] const_cast<XMLCh*>(m_name);
        delete[] const_cast<XMLCh*>(m_namespace);
    }
    delete m_type;
}

SAMLObject* SAMLAttribute::clone() const
{
    SAMLAttribute* dest=new SAMLAttribute(m_name,m_namespace,m_type,m_lifetime);
    dest->m_values.assign(m_values.begin(),m_values.end());
    return dest;
}

void SAMLAttribute::fromDOM(DOMElement* e)
{
    saml::NDC ndc("fromDOM");
    SAMLObject::fromDOM(e);
    if (SAMLConfig::getConfig().strict_dom_checking &&
        (XMLString::compareString(XML::SAML_NS,e->getNamespaceURI()) ||
            ((XMLString::compareString(L(Attribute),e->getLocalName()) && XMLString::compareString(L(AttributeDesignator),e->getLocalName())))))
            throw MalformedException(SAMLException::RESPONDER,"SAMLAttribute::fromDOM() missing saml:Attribute[Designator] element at root");

    m_root=e;
    m_bOwnStrings=false;
    m_name=e->getAttributeNS(NULL,L(AttributeName));
    m_namespace=e->getAttributeNS(NULL,L(AttributeNamespace));
}

DOMNode* SAMLAttribute::toDOM(DOMDocument* doc, bool xmlns) const
{
    SAMLObject::toDOM(doc,xmlns);
    if (m_root)
    {
        if (xmlns)
        {
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,xsi),XML::XSI_NS);
            static_cast<DOMElement*>(m_root)->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,xsd),XML::XSD_NS);
        }
        return m_root;
    }
    if (!doc)
        doc=m_document;

    // Construct the Attribute.
    DOMElement* a=doc->createElementNS(XML::SAML_NS,L(Attribute));
    if (xmlns)
        a->setAttributeNS(XML::XMLNS_NS,L(xmlns),XML::SAML_NS);
    a->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,xsi),XML::XSI_NS);
    a->setAttributeNS(XML::XMLNS_NS,L_QNAME(xmlns,xsd),XML::XSD_NS);
    a->setAttributeNS(NULL,L(AttributeName),m_name);
    a->setAttributeNS(NULL,L(AttributeNamespace),m_namespace);

    xstring xsitype;
    if (m_type)
    {
        if (!XMLString::compareString(XML::XSD_NS,m_type->getNamespaceURI()))
            xsitype = chLatin_x + chLatin_s + chLatin_d;
        else
            xsitype = chLatin_t + chLatin_y + chLatin_p + chLatin_e + chLatin_n + chLatin_s;
        xsitype = xsitype + chColon + m_type->getLocalName();
    }

    for (vector<xstring>::const_iterator i = m_values.begin(); i!=m_values.end(); i++)
    {
        DOMElement* v = doc->createElementNS(XML::SAML_NS,L(AttributeValue));
        if (m_type)
            v->setAttributeNS(XML::XSI_NS, L(type), xsitype.c_str());
        v->appendChild(doc->createTextNode(i->c_str()));
        a->appendChild(v);
    }

    return m_root=a;
}

Iterator<string> SAMLAttribute::getSingleByteValues() const
{
    if (m_sbValues.empty())
    {
        for (vector<xstring>::const_iterator i=m_values.begin(); i!=m_values.end(); i++)
        {
            auto_ptr<char> temp(toUTF8(i->c_str()));
            if (temp.get())
                m_sbValues.push_back(temp.get());
        }
    }
    return Iterator<string>(m_sbValues);
}

bool SAMLAttribute::addValue(DOMElement* e)
{
    DOMNode* n=e->getFirstChild();
    if (accept(e))
    {
        const XMLCh* ptr=NULL;
        if (n->getNodeType()==DOMNode::TEXT_NODE && (ptr=n->getNodeValue()))
        {
            m_values.push_back(ptr);
            return true;
        }
        saml::NDC ndc("addValue");
        SAML_log.warn("rejecting an AttributeValue without a simple, non-empty text node");
    }
    return false;
}
