#include "databasemanager.h"

#include <QDebug>
#include <QMessageBox>
#include <QSqlError>

#include "global.h"
#include "logger.h"

DatabaseManager& DatabaseManager::getInstance() {
    static DatabaseManager instance;
    return instance;
}

// 创建一个新的数据库连接
DatabaseManager::DatabaseManager() : db(QSqlDatabase::addDatabase("QMYSQL")) {
    db.setHostName(databaseHost);
    db.setDatabaseName("pc_system");
    db.setUserName("root");
    db.setPassword("123456");

    if (!db.open()) {
        Logger::getInstance().error(QString("Mysql Connected error. host: %1, error: %2")
                                        .arg(databaseHost, db.lastError().text()));
        QMessageBox::critical(
            nullptr, "错误",
            QString("无法连接数据库, 请联系开发人员。\n 错误: %1").arg(db.lastError().text()));

        throw std::runtime_error("Database connection failed: " +
                                 db.lastError().text().toStdString());
    }
    Logger::getInstance().info(QString("Mysql Connected. host: %1").arg(databaseHost));
}

DatabaseManager::~DatabaseManager() {
    if (db.isOpen()) {
        db.close();
    }
}

QSqlDatabase& DatabaseManager::getDatabase() { return db; }
