#include "dbStructureNode.h"
#include <QSqlDatabase>
#include <QSqlQuery>

DBStructureNode::DBStructureNode(NodeType type, const QString& name, DBStructureNode* parent)
    : m_type(type), m_name(name), m_parent(parent)
{
    switch (m_type)
    {
    case RootNode:
    {
        m_status = NoStatus;
        m_icon = QIcon(":img/images/icon_postgresql.png");
        break;
    }
    case ConnectionNode:
    {
        m_status = Disconnect; //初始化为未连接，双击进行链接
        m_icon = QIcon(":img/images/icon_db_disconnect.png");
        break;
    }
    case DatabaseNode:
    {
        m_status = NoStatus;
        m_icon = QIcon(":img/images/icon_database.png");
        break;
    }
    case TableNode:
    {
        m_status = NoStatus;
        m_icon = QIcon(":img/images/icon_table.png");
        break;
    }
    case GroupNode:
    {
        m_status = NoStatus;
        m_icon = QIcon(":img/images/icon_hierarchy.png");
        break;
    }
    default:
        break;
    }
}

DBStructureNode::~DBStructureNode()
{
    qDeleteAll(m_children);
}

//节点操作
void DBStructureNode::appendChild(DBStructureNode* child)
{
    if(child)
    {
        child->m_parent = this; // 成员函数可以访问同一类的其他对象的私有成员
        m_children.append(child);
    }
}

DBStructureNode* DBStructureNode::child(int row)
{
    if(row < 0 || row >= m_children.count())
        return nullptr;

    return m_children.value(row);
}

int DBStructureNode::childCount() const
{
    return m_children.count();
}

int DBStructureNode::row() const
{
    if(m_parent)
        return m_parent->m_children.indexOf(this);

    return 0;
}

void DBStructureNode::removeAllChildren()
{
    qDeleteAll(m_children);
    m_children.clear();
}

//数据访问
NodeType DBStructureNode::type() const
{
    return m_type;
}

QString DBStructureNode::name() const
{
    return m_name;
}

QIcon DBStructureNode::icon() const
{
    return m_icon;
}

void DBStructureNode::setStatus(NodeStatus status)
{
    m_status = status;

    if(m_type == ConnectionNode && status == Disconnect)
        m_icon = QIcon(":img/images/icon_db_disconnect.png");
    else if(m_type == ConnectionNode && status == Connect)
        m_icon = QIcon(":img/images/icon_db_connect.png");
}

NodeStatus DBStructureNode::status() const
{
    return m_status;
}

QVariant DBStructureNode::columnData(int column) const
{
     switch(column)
    {
    case ColumnName:
         return m_name;
    default:
        return QVariant();
    }
}

DBStructureNode* DBStructureNode::parentNode()
{
    return m_parent;
}

void DBStructureNode::setData(int role, const QVariant& value)
{
    m_roleData[role] = value;
}

QVariant DBStructureNode::data(int role) const
{
    return m_roleData.value(role, QVariant()); //不存在则返回空QVariant
}
