#include "cmwauthoritymanager.h"
#include "ui_cmwauthoritymanager.h"

#include "cmwauthoritypermission.h"
#include "cmwauthorityrole.h"
#include "cmwauthorityuser.h"

CMWAuthorityManager::CMWAuthorityManager(QWidget* parent)
    : QWidget(parent)
{
    ui = new Ui::CMWAuthorityManager();

    QGridLayout* layout = new QGridLayout(parent);
    QTabWidget* tabWidget = new QTabWidget(parent);

    CSqliteAuthorityManager* authorityInstance = new CSqliteAuthorityManager;
    authorityInstance->Init();
    authorityInstance->LoginUserChanged = std::function<void()>(std::bind(&CMWAuthorityManager::FreshAuthority, this));

    CMWAuthorityUser* userManager = new CMWAuthorityUser(parent);
    userManager->SetAuthorityManager(authorityInstance);

    CMWAuthorityPermission* permissionManager = new CMWAuthorityPermission(parent);
    permissionManager->SetAuthorityManager(authorityInstance);

    CMWAuthorityRole* roleManager = new CMWAuthorityRole(parent);
    roleManager->SetAuthorityManager(authorityInstance);

    childWidgets.push_back(userManager);
    childWidgets.push_back(permissionManager);
    childWidgets.push_back(roleManager);

    tabWidget->addTab(userManager, tr("UserManager"));
    tabWidget->addTab(roleManager, tr("RoleManager"));
    tabWidget->addTab(permissionManager, tr("PermissionManager"));

    layout->addWidget(tabWidget);
    layout->setMargin(0);
    layout->setSpacing(0);
    setLayout(layout);

    ui->setupUi(this);

    connect(this, &CMWAuthorityManager::SendFreshAuthority, this, &CMWAuthorityManager::FreshAllAuthority, Qt::QueuedConnection);
}

CMWAuthorityManager::~CMWAuthorityManager()
{
    delete ui;
}

void CMWAuthorityManager::FreshAuthority()
{
    emit SendFreshAuthority();
}

void CMWAuthorityManager::FreshAllAuthority()
{
    for (int i = 0; i < childWidgets.size(); i++) {
        childWidgets[i]->FreshAuthority();
    }
}
