/*****************************************************************************
*
* Copyright (c) 2000 - 2018, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* 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 disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS 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.
*
*****************************************************************************/

#include <HostProfileList.h>
#include <DataNode.h>
#include <MachineProfile.h>

// ****************************************************************************
// Method: HostProfileList::HostProfileList
//
// Purpose: 
//   Init utility for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void HostProfileList::Init()
{

    HostProfileList::SelectAll();
}

// ****************************************************************************
// Method: HostProfileList::HostProfileList
//
// Purpose: 
//   Copy utility for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void HostProfileList::Copy(const HostProfileList &obj)
{
    AttributeGroupVector::const_iterator pos;

    // *** Copy the machines field ***
    // Delete the AttributeGroup objects and clear the vector.
    for(pos = machines.begin(); pos != machines.end(); ++pos)
        delete *pos;
    machines.clear();
    if(obj.machines.size() > 0)
        machines.reserve(obj.machines.size());
    // Duplicate the machines from obj.
    for(pos = obj.machines.begin(); pos != obj.machines.end(); ++pos)
    {
        MachineProfile *oldMachineProfile = (MachineProfile *)(*pos);
        MachineProfile *newMachineProfile = new MachineProfile(*oldMachineProfile);
        machines.push_back(newMachineProfile);
    }


    HostProfileList::SelectAll();
}

// Type map format string
const char *HostProfileList::TypeMapFormatString = HOSTPROFILELIST_TMFS;
const AttributeGroup::private_tmfs_t HostProfileList::TmfsStruct = {HOSTPROFILELIST_TMFS};


// ****************************************************************************
// Method: HostProfileList::HostProfileList
//
// Purpose: 
//   Default constructor for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

HostProfileList::HostProfileList() : 
    AttributeSubject(HostProfileList::TypeMapFormatString)
{
    HostProfileList::Init();
}

// ****************************************************************************
// Method: HostProfileList::HostProfileList
//
// Purpose: 
//   Constructor for the derived classes of HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

HostProfileList::HostProfileList(private_tmfs_t tmfs) : 
    AttributeSubject(tmfs.tmfs)
{
    HostProfileList::Init();
}

// ****************************************************************************
// Method: HostProfileList::HostProfileList
//
// Purpose: 
//   Copy constructor for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

HostProfileList::HostProfileList(const HostProfileList &obj) : 
    AttributeSubject(HostProfileList::TypeMapFormatString)
{
    HostProfileList::Copy(obj);
}

// ****************************************************************************
// Method: HostProfileList::HostProfileList
//
// Purpose: 
//   Copy constructor for derived classes of the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

HostProfileList::HostProfileList(const HostProfileList &obj, private_tmfs_t tmfs) : 
    AttributeSubject(tmfs.tmfs)
{
    HostProfileList::Copy(obj);
}

// ****************************************************************************
// Method: HostProfileList::~HostProfileList
//
// Purpose: 
//   Destructor for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

HostProfileList::~HostProfileList()
{
    AttributeGroupVector::iterator pos;

    // Destroy the machines field.
    for(pos = machines.begin(); pos != machines.end(); ++pos)
        delete *pos;
}

// ****************************************************************************
// Method: HostProfileList::operator = 
//
// Purpose: 
//   Assignment operator for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

HostProfileList& 
HostProfileList::operator = (const HostProfileList &obj)
{
    if (this == &obj) return *this;

    HostProfileList::Copy(obj);

    return *this;
}

// ****************************************************************************
// Method: HostProfileList::operator == 
//
// Purpose: 
//   Comparison operator == for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

bool
HostProfileList::operator == (const HostProfileList &obj) const
{
    bool machines_equal = (obj.machines.size() == machines.size());
    for(size_t i = 0; (i < machines.size()) && machines_equal; ++i)
    {
        // Make references to MachineProfile from AttributeGroup *.
        const MachineProfile &machines1 = *((const MachineProfile *)(machines[i]));
        const MachineProfile &machines2 = *((const MachineProfile *)(obj.machines[i]));
        machines_equal = (machines1 == machines2);
    }

    // Create the return value
    return (machines_equal);
}

// ****************************************************************************
// Method: HostProfileList::operator != 
//
// Purpose: 
//   Comparison operator != for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

bool
HostProfileList::operator != (const HostProfileList &obj) const
{
    return !(this->operator == (obj));
}

// ****************************************************************************
// Method: HostProfileList::TypeName
//
// Purpose: 
//   Type name method for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

const std::string
HostProfileList::TypeName() const
{
    return "HostProfileList";
}

// ****************************************************************************
// Method: HostProfileList::CopyAttributes
//
// Purpose: 
//   CopyAttributes method for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

bool
HostProfileList::CopyAttributes(const AttributeGroup *atts)
{
    if(TypeName() != atts->TypeName())
        return false;

    // Call assignment operator.
    const HostProfileList *tmp = (const HostProfileList *)atts;
    *this = *tmp;

    return true;
}

// ****************************************************************************
// Method: HostProfileList::CreateCompatible
//
// Purpose: 
//   CreateCompatible method for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

AttributeSubject *
HostProfileList::CreateCompatible(const std::string &tname) const
{
    AttributeSubject *retval = 0;
    if(TypeName() == tname)
        retval = new HostProfileList(*this);
    // Other cases could go here too. 

    return retval;
}

// ****************************************************************************
// Method: HostProfileList::NewInstance
//
// Purpose: 
//   NewInstance method for the HostProfileList class.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

AttributeSubject *
HostProfileList::NewInstance(bool copy) const
{
    AttributeSubject *retval = 0;
    if(copy)
        retval = new HostProfileList(*this);
    else
        retval = new HostProfileList;

    return retval;
}

// ****************************************************************************
// Method: HostProfileList::SelectAll
//
// Purpose: 
//   Selects all attributes.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void
HostProfileList::SelectAll()
{
    Select(ID_machines, (void *)&machines);
}

// ****************************************************************************
// Method: HostProfileList::CreateSubAttributeGroup
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

AttributeGroup *
HostProfileList::CreateSubAttributeGroup(int)
{
    return new MachineProfile;
}

///////////////////////////////////////////////////////////////////////////////
// Persistence methods
///////////////////////////////////////////////////////////////////////////////

// ****************************************************************************
// Method: HostProfileList::CreateNode
//
// Purpose: 
//   This method creates a DataNode representation of the object so it can be saved to a config file.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

bool
HostProfileList::CreateNode(DataNode *parentNode, bool completeSave, bool forceAdd)
{
    if(parentNode == 0)
        return false;

    HostProfileList defaultObject;
    bool addToParent = false;
    // Create a node for HostProfileList.
    DataNode *node = new DataNode("HostProfileList");

    if(completeSave || !FieldsEqual(ID_machines, &defaultObject))
    {
        addToParent = true;
        for(size_t i = 0; i < machines.size(); ++i)
            machines[i]->CreateNode(node, completeSave, true);
    }


    // Add the node to the parent node.
    if(addToParent || forceAdd)
        parentNode->AddNode(node);
    else
        delete node;

    return (addToParent || forceAdd);
}

// ****************************************************************************
// Method: HostProfileList::SetFromNode
//
// Purpose: 
//   This method sets attributes in this object from values in a DataNode representation of the object.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void
HostProfileList::SetFromNode(DataNode *parentNode)
{
    if(parentNode == 0)
        return;

    DataNode *searchNode = parentNode->GetNode("HostProfileList");
    if(searchNode == 0)
        return;

    DataNode **children;

    // Clear all the MachineProfiles if we got any.
    bool clearedMachines = false;
    // Go through all of the children and construct a new
    // MachineProfile for each one of them.
    children = searchNode->GetChildren();
    if(children != 0)
    {
        for(int i = 0; i < searchNode->GetNumChildren(); ++i)
        {
            if(children[i]->GetKey() == std::string("MachineProfile"))
            {
                if (!clearedMachines)
                {
                    ClearMachines();
                    clearedMachines = true;
                }
                MachineProfile temp;
                temp.SetFromNode(children[i]);
                AddMachines(temp);
            }
        }
    }

}

///////////////////////////////////////////////////////////////////////////////
// Set property methods
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Get property methods
///////////////////////////////////////////////////////////////////////////////

const AttributeGroupVector &
HostProfileList::GetMachines() const
{
    return machines;
}

AttributeGroupVector &
HostProfileList::GetMachines()
{
    return machines;
}

///////////////////////////////////////////////////////////////////////////////
// Select property methods
///////////////////////////////////////////////////////////////////////////////

void
HostProfileList::SelectMachines()
{
    Select(ID_machines, (void *)&machines);
}

///////////////////////////////////////////////////////////////////////////////
// AttributeGroupVector convenience methods.
///////////////////////////////////////////////////////////////////////////////

// ****************************************************************************
// Method: HostProfileList::AddMachines
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void
HostProfileList::AddMachines(const MachineProfile &obj)
{
    MachineProfile *newMachineProfile = new MachineProfile(obj);
    machines.push_back(newMachineProfile);

    // Indicate that things have changed by selecting it.
    Select(ID_machines, (void *)&machines);
}

// ****************************************************************************
// Method: HostProfileList::ClearMachines
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void
HostProfileList::ClearMachines()
{
    AttributeGroupVector::iterator pos;

    for(pos = machines.begin(); pos != machines.end(); ++pos)
        delete *pos;
    machines.clear();

    // Indicate that things have changed by selecting the list.
    Select(ID_machines, (void *)&machines);
}

// ****************************************************************************
// Method: HostProfileList::RemoveMachines
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

void
HostProfileList::RemoveMachines(int index)
{
    AttributeGroupVector::iterator pos = machines.begin();

    // Iterate through the vector "index" times. 
    for(int i = 0; i < index; ++i)
        if(pos != machines.end()) ++pos;

    // If pos is still a valid iterator, remove that element.
    if(pos != machines.end())
    {
        delete *pos;
        machines.erase(pos);
    }

    // Indicate that things have changed by selecting the list.
    Select(ID_machines, (void *)&machines);
}

// ****************************************************************************
// Method: HostProfileList::GetNumMachines
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

int
HostProfileList::GetNumMachines() const
{
    return (int)machines.size();
}

// ****************************************************************************
// Method: HostProfileList::GetMachines
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

MachineProfile &
HostProfileList::GetMachines(int i)
{
    return *((MachineProfile *)machines[i]);
}

// ****************************************************************************
// Method: HostProfileList::GetMachines
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

const MachineProfile &
HostProfileList::GetMachines(int i) const
{
    return *((MachineProfile *)machines[i]);
}

// ****************************************************************************
// Method: HostProfileList::operator []
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

MachineProfile &
HostProfileList::operator [] (int i)
{
    return *((MachineProfile *)machines[i]);
}

// ****************************************************************************
// Method: HostProfileList::operator []
//
// Purpose: 
//   This class contains a list of host profiles.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

const MachineProfile &
HostProfileList::operator [] (int i) const
{
    return *((MachineProfile *)machines[i]);
}

///////////////////////////////////////////////////////////////////////////////
// Keyframing methods
///////////////////////////////////////////////////////////////////////////////

// ****************************************************************************
// Method: HostProfileList::GetFieldName
//
// Purpose: 
//   This method returns the name of a field given its index.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

std::string
HostProfileList::GetFieldName(int index) const
{
    switch (index)
    {
    case ID_machines: return "machines";
    default:  return "invalid index";
    }
}

// ****************************************************************************
// Method: HostProfileList::GetFieldType
//
// Purpose: 
//   This method returns the type of a field given its index.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

AttributeGroup::FieldType
HostProfileList::GetFieldType(int index) const
{
    switch (index)
    {
    case ID_machines: return FieldType_attVector;
    default:  return FieldType_unknown;
    }
}

// ****************************************************************************
// Method: HostProfileList::GetFieldTypeName
//
// Purpose: 
//   This method returns the name of a field type given its index.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

std::string
HostProfileList::GetFieldTypeName(int index) const
{
    switch (index)
    {
    case ID_machines: return "attVector";
    default:  return "invalid index";
    }
}

// ****************************************************************************
// Method: HostProfileList::FieldsEqual
//
// Purpose: 
//   This method compares two fields and return true if they are equal.
//
// Note:       Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation:   omitted
//
// Modifications:
//   
// ****************************************************************************

bool
HostProfileList::FieldsEqual(int index_, const AttributeGroup *rhs) const
{
    const HostProfileList &obj = *((const HostProfileList*)rhs);
    bool retval = false;
    switch (index_)
    {
    case ID_machines:
        {  // new scope
        bool machines_equal = (obj.machines.size() == machines.size());
        for(size_t i = 0; (i < machines.size()) && machines_equal; ++i)
        {
            // Make references to MachineProfile from AttributeGroup *.
            const MachineProfile &machines1 = *((const MachineProfile *)(machines[i]));
            const MachineProfile &machines2 = *((const MachineProfile *)(obj.machines[i]));
            machines_equal = (machines1 == machines2);
        }

        retval = machines_equal;
        }
        break;
    default: retval = false;
    }

    return retval;
}

///////////////////////////////////////////////////////////////////////////////
// User-defined methods.
///////////////////////////////////////////////////////////////////////////////

// ****************************************************************************
//  Method: HostProfileList::GetActiveLaunchProfileForHost
//
//  Purpose: 
//    Returns the active launch profile for the machine with a host name
//    pattern matching the specified host name.
//
//  Arguments:
//    hostName    the host name to match with the profile hostname patterns
//   
//  Returns:    
//    A pointer to the host profile, or NULL.
//
//  Programmer: Jeremy Meredith
//  Creation:   February 18, 2010
//
//  Modifications:
//
// ****************************************************************************
LaunchProfile *
HostProfileList::GetActiveLaunchProfileForHost(const std::string &hostName) const
{   
    MachineProfile *machine = GetMachineProfileForHost(hostName);
    return machine ? machine->GetActiveLaunchProfile() : NULL;
}

// ****************************************************************************
//  Method: HostProfileList::GetMachineProfileForHost
//
//  Purpose: 
//    Gets the machine profile with a host name pattern
//    matching the specified host name.
//
//  Arguments:
//    hostName    the host name to match with the profile hostname patterns
//   
//  Returns:    
//    A pointer to the machine profile, or NULL.
//
//  Programmer: Jeremy Meredith
//  Creation:   February 18, 2010
//
//  Modifications:
//    Brad Whitlock, Tue May 20 11:53:37 PDT 2003
//    I moved these include files to here so we can successfully regenerate
//    the class.
//
//    Jeremy Meredith, Fri Feb 26 09:28:01 EST 2010
//    Try matching against the original hostname if matching against the
//    resolved host name fails.
//
//    David Camp, Fri Feb 26 13:53:28 PST 2010
//    Try matching against all of the host's aliases.
// ****************************************************************************
#if defined(_WIN32)
#include <winsock2.h>
#else
#include <netdb.h>
#endif

MachineProfile *
HostProfileList::GetMachineProfileForHost(const std::string &hostName) const
{
    // Check for the hostname
    for(size_t i = 0; i < machines.size(); i++)
    {
        MachineProfile *m = (MachineProfile *)(machines[i]);

        if (m->ProfileMatchesHost(hostName))
            return m;
    }

    struct hostent *hostEnt = gethostbyname(hostName.c_str());
    if (hostEnt)
    {
        // Check for the official host name
        std::string fqhostName(hostEnt->h_name);
        for(size_t i = 0; i < machines.size(); i++)
        {
            MachineProfile *m = (MachineProfile *)(machines[i]);

            if (m->ProfileMatchesHost(fqhostName))
                return m;
        }

        // Check all of the aliases
        for(int j=0; hostEnt->h_aliases[j] != NULL; j++)
        {
            fqhostName = std::string(hostEnt->h_aliases[j]);
            for(size_t i = 0; i < machines.size(); i++)
            {
                MachineProfile *m = (MachineProfile *)(machines[i]);

                if (m->ProfileMatchesHost(fqhostName))
                    return m;
            }
        }
    }

    return NULL;
}

