#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include "dbManager.h"
#include "connectionDialog.h"
#include "dbStructureView.h"
#include "dbStructureModel.h"
#include "logger.h"
#include "sqlQueryExecutor.h"
#include "modelInfoEditDialog.h"

#include <QKeyEvent>
#include <QScreen>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_dbManager(nullptr)
    , m_pMessageDialog(nullptr)
    , m_pConnectionDialog(nullptr)
    , m_pModelInfoDialog(nullptr)
{
    ui->setupUi(this);

    initialize();
}

MainWindow::~MainWindow()
{
    delete ui;
    LOG_INFO("Application", "------------------------------------------------Application exit------------------------------------------------");
}

bool MainWindow::eventFilter(QObject* obj, QEvent* event)
{
    QDialog *pDialog = qobject_cast<QDialog*>(obj);
    if(pDialog)
    {
        if(event->type() == QEvent::KeyPress)
        {
            QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(event);
            if (pKeyEvent->key() == Qt::Key_Escape)
            {
                return true;
            }
        }
    }
    return QObject::eventFilter(obj, event);
}

void MainWindow::initialize()
{    
    connect(ui->connectAction, &QAction::triggered, this, &MainWindow::onActionTrigger_connect);
    connect(ui->disconnectAction, &QAction::triggered, this, &MainWindow::onActionTrigger_disconnect);

    connect(ui->createTableAction, &QAction::triggered, this, &MainWindow::onActionTrigger_addModel);
    connect(ui->deleteTableAction, &QAction::triggered, this, &MainWindow::onActionTrigger_removeModel);

    connect(&SqlQueryExecutor::instance(), &SqlQueryExecutor::errorOccurred, this, &MainWindow::onSIG_errorFormSQLExecutor);

    m_dbManager = new DatabaseManager(this);
    connect(m_dbManager, &DatabaseManager::errorOccurred, this, &MainWindow::onSIG_errorFromDBManger);
    connect(m_dbManager, &DatabaseManager::connectionStatusChanged, this, &MainWindow::onSIG_connectionStatusChanged);

    m_pDBStrutureView = new DBStructureView(m_dbManager, this);
    connect(m_pDBStrutureView, &DBStructureView::actionTrigger_addModel, this, &MainWindow::onActionTrigger_addModel);
    ui->layoutDBStructure->addWidget(m_pDBStrutureView);
    m_pDBStrutureModel = new DBStructureModel(this);
    m_pDBStrutureView->setModel(m_pDBStrutureModel);

    QScreen* screen = this->screen();
    int nWidth = screen->size().width() * 0.8;
    int nHeight = screen->size().height() * 0.8;
    this->resize(nWidth, nHeight);
    ui->splitter->setStretchFactor(0, 1);
    ui->splitter->setStretchFactor(1, 10);
}

void MainWindow::showMessageDialog(MessageDialogType type,const QString& strTitle,const QString& strContent)
{
    if(m_pMessageDialog == nullptr)
    {
        m_pMessageDialog = new MessageDialog(this);
        m_pMessageDialog->installEventFilter(this);
    }

    m_pMessageDialog->setMessage(type, strTitle, strContent);
    int nX = this->geometry().x() + (this->width() - m_pMessageDialog->width()) * 0.5;
    int nY = this->geometry().y() + (this->height() - m_pMessageDialog->height()) * 0.5;
    m_pMessageDialog->move(nX, nY);
    //m_pMessageDialog->raise();
    // if(type == type_question)
    //     m_pMessageDialog->exec();
    // else
    //     m_pMessageDialog->show();
    m_pMessageDialog->exec();
}
void MainWindow::hideMessageDialog()
{
    if(m_pMessageDialog && m_pMessageDialog->isVisible())
        m_pMessageDialog->close();
}

const QString MainWindow::getCurConnection()
{
    if(m_pDBStrutureView)
        return m_pDBStrutureView->curConnection();
    else
        return QString("");
}

void MainWindow::onActionTrigger_connect()
{
    if(m_pConnectionDialog && m_pConnectionDialog->isVisible())
        return;

    // if(m_dbManager->conncetions().count() >=1 ) //暂时只支持一个链接
    // {
    //     showMessageDialog(type_information, QString::fromWCharArray(L"提示"), QString::fromWCharArray(L"若要开启新的图模库链接，请先断开当前链接"));
    //     return;
    // }

    if(m_pConnectionDialog == nullptr)
    {
        m_pConnectionDialog = new ConnectionDialog(this);
        m_pConnectionDialog->setMainWindow(this);
        m_pConnectionDialog->installEventFilter(this);
        connect(m_pConnectionDialog, &ConnectionDialog::addConnection, this, &MainWindow::onSIG_addConnection);
    }

    int nX = this->geometry().x() + (this->width() - m_pConnectionDialog->width()) * 0.5;
    int nY = this->geometry().y() + (this->height() - m_pConnectionDialog->height()) * 0.5;
    m_pConnectionDialog->move(nX, nY);
    m_pConnectionDialog->exec();
}
void MainWindow::onActionTrigger_disconnect()
{
    if(m_pDBStrutureView)
        m_pDBStrutureView->disconnectCurConnection();
}

void MainWindow::onActionTrigger_addModel()
{
    if(m_pModelInfoDialog && m_pModelInfoDialog->isVisible())
        return;

    if(m_pModelInfoDialog == nullptr)
    {
        m_pModelInfoDialog = new ModelInfoEditDialog(this);
        m_pModelInfoDialog->setMainWindow(this);
        m_pModelInfoDialog->installEventFilter(this);
        connect(m_pModelInfoDialog, &ModelInfoEditDialog::addModel, this, &MainWindow::onSIG_addModel);
    }

    int nX = this->geometry().x() + (this->width() - m_pModelInfoDialog->width()) * 0.5;
    int nY = this->geometry().y() + (this->height() - m_pModelInfoDialog->height()) * 0.5;
    m_pModelInfoDialog->move(nX, nY);
    m_pModelInfoDialog->setState(DS_New);
    m_pModelInfoDialog->exec();
}
void MainWindow::onActionTrigger_removeModel()
{

}

void MainWindow::onSIG_addConnection(DatabaseConfig& config)
{
    bool result = m_dbManager->addDatabase(config);
    if(!result)
    {
        //m_pConnectionDialog->setErrorInfo(m_lastSqlError.databaseText());
        return;
    }

    m_pConnectionDialog->close();
    m_pDBStrutureModel->addConnection(config.strConnectionName, config.strDBType);
}

void MainWindow::onSIG_errorFromDBManger(const QString& strConnectionName, const QSqlError& error)
{
    m_lastSqlError = error;
    showMessageDialog(type_warning, QString::fromWCharArray(L"错误"),error.databaseText());
}

void MainWindow::onSIG_errorFormSQLExecutor(const QString& error)
{
    showMessageDialog(type_warning, QString::fromWCharArray(L"错误"),error);
}

void MainWindow::onSIG_connectionStatusChanged(const QString& strConnectionName, bool bConnected)
{
    ui->createTableAction->setEnabled(bConnected);
    ui->deleteTableAction->setEnabled(bConnected);
    ui->importAciton->setEnabled(bConnected);
    ui->exportAction->setEnabled(bConnected);
    ui->refreshAction->setEnabled(bConnected);
    ui->saveAction->setEnabled(bConnected);
}

void MainWindow::onSIG_addModel(Model& model)
{
    QString connection = m_pDBStrutureView->curConnection();
    m_pDBStrutureModel->addDataModel(connection, model);
}
