#include "mainwindow.h"

#include "graphicsItem/graphicsItemGroup.h"
#include "ui_mainwindow.h"

#include <QWidgetAction>
#include <QTableWidget>
#include <QSettings>
#include <QUndoStack>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QFileInfo>

#include "DockAreaWidget.h"
#include "DockAreaTitleBar.h"
#include "DockAreaTabBar.h"
#include "FloatingDockContainer.h"
#include "DockComponentsFactory.h"

#include "QQuickDetailsViewMananger.h"
#include "propertyType/PropertyTypeCustomization_CustomType.h"
#include "propertyType/CustomType.h"
#include "QDetailsView.h"
#include "util/selectorManager.h"

#include "drawingPanel.h"
#include "designerScene.h"
#include "graphicElementsPanel.h"
#include "operationCommand.h"
#include "document.h"

using namespace ads;


CMainWindow::CMainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::CMainWindow)
{
    ui->setupUi(this);
    m_pDocument = new Document(this);

    initializeDockUi();
    initializeAction();

    connect(m_pGraphicElementsPanel,SIGNAL(addGraphicsItem(GraphicsItemType&)),m_pDrawingPanel,SLOT(onSignal_addGraphicsItem(GraphicsItemType&)));
}

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


void CMainWindow::closeEvent(QCloseEvent* event)
{
    if (!maybeSave()) {
        event->ignore();
        return;
    }
    m_pDockManager->deleteLater();
    QMainWindow::closeEvent(event);
}

void CMainWindow::changeEvent(QEvent* event)
{
    if (event->type() == QEvent::WindowStateChange)
        m_pDrawingPanel->grahpicsViewZoomFit();
}

void CMainWindow::initializeDockUi()
{
    CDockManager::setConfigFlag(CDockManager::OpaqueSplitterResize, true);
    CDockManager::setConfigFlag(CDockManager::XmlCompressionEnabled, false);
    CDockManager::setConfigFlag(CDockManager::FocusHighlighting, true);
    m_pDockManager = new CDockManager(this);

    // Set central widget
    m_pDrawingPanel = new DrawingPanel();
    m_pDrawingPanel->setScene(m_pDocument->scene());
    DesignerScene* designerScene = m_pDocument->scene();
    connect(designerScene, SIGNAL(signalAddItem(QGraphicsItem*)), this, SLOT(onSignal_addItem(QGraphicsItem*)));
    connect(designerScene, SIGNAL(selectionChanged()), this, SLOT(onSignal_selectionChanged()));
    CDockWidget* CentralDockWidget = new CDockWidget("CentralWidget");
    CentralDockWidget->setWidget(m_pDrawingPanel);
    auto* centralDockArea = m_pDockManager->setCentralWidget(CentralDockWidget);
    centralDockArea->setAllowedAreas(DockWidgetArea::OuterDockAreas);

    // create other dock widgets
    m_pGraphicElementsPanel = new GraphicElementsPanel();
    CDockWidget* GrapicElementsDockWidget = new CDockWidget(QString::fromWCharArray(L"图元面板"));
    GrapicElementsDockWidget->setWidget(m_pGraphicElementsPanel);
    GrapicElementsDockWidget->setMinimumSizeHintMode(CDockWidget::MinimumSizeHintFromDockWidget);
    GrapicElementsDockWidget->resize(400, 150);
    GrapicElementsDockWidget->setMinimumSize(200,150);
    m_pDockManager->addDockWidget(DockWidgetArea::LeftDockWidgetArea, GrapicElementsDockWidget);
    ui->menuView->addAction(GrapicElementsDockWidget->toggleViewAction());

	QQuickDetailsViewManager::Get()->registerPropertyTypeCustomization<QCustomType, PropertyTypeCustomization_CustomType>();

    m_pPropertiesEditorView = new QDetailsView();
    CDockWidget* propertiesDockWidget = new CDockWidget(QString::fromWCharArray(L"属性编辑器"));
    propertiesDockWidget->setWidget(m_pPropertiesEditorView);
    propertiesDockWidget->setMinimumSizeHintMode(CDockWidget::MinimumSizeHintFromDockWidget);
    propertiesDockWidget->resize(550, 150);
    propertiesDockWidget->setMinimumSize(500,150);
    m_pPropertiesEditorView->setObject(m_pDocument->scene());
    m_pDockManager->addDockWidget(DockWidgetArea::RightDockWidgetArea, propertiesDockWidget, centralDockArea);
    ui->menuView->addAction(propertiesDockWidget->toggleViewAction());
}

void CMainWindow::initializeAction()
{
    //撤销、重做
    QUndoStack *undoStack = m_pDocument->undoStack();
    ui->actionUndo = undoStack->createUndoAction(this, tr("撤销"));
    ui->actionUndo->setIcon(QIcon::fromTheme(QString::fromUtf8("edit-undo")));
    ui->actionUndo->setShortcuts(QKeySequence::Undo);
    ui->actionRedo = undoStack->createRedoAction(this, tr("重做"));
    ui->actionRedo->setIcon(QIcon::fromTheme(QString::fromUtf8("edit-redo")));
    ui->actionRedo->setShortcuts(QKeySequence::Redo);
    ui->toolBar->addAction(ui->actionUndo);
    ui->toolBar->addAction(ui->actionRedo);

    ui->actionDelete->setShortcut(QKeySequence::Delete);

    connect(ui->actionDelete, SIGNAL(triggered()), this, SLOT(onSignal_deleteItem()));
    connect(ui->actionZoomIn, SIGNAL(triggered()), this, SLOT(onAction_zoomIn()));
    connect(ui->actionZoomOut, SIGNAL(triggered()), this, SLOT(onAction_zoomOut()));
    connect(ui->actionZoomFit, SIGNAL(triggered()), this, SLOT(onAction_zoomFit()));
    connect(ui->actionGroup, SIGNAL(triggered()), this, SLOT(onAction_createGroup()));
    connect(ui->actionUngroup, SIGNAL(triggered()), this, SLOT(onAction_destroyGroup()));

    // File actions
    connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(onAction_new()));
    connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(onAction_open()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(onAction_save()));

    // Save As — created in code since not in .ui
    QAction *actionSaveAs = new QAction(QIcon::fromTheme("document-save-as"), tr("另存为..."), this);
    actionSaveAs->setShortcut(QKeySequence::SaveAs);
    ui->toolBar->addAction(actionSaveAs);
    connect(actionSaveAs, SIGNAL(triggered()), this, SLOT(onAction_saveAs()));

    // Populate File menu
    ui->menuFile->addAction(ui->actionNew);
    ui->menuFile->addAction(ui->actionOpen);
    ui->menuFile->addAction(ui->actionSave);
    ui->menuFile->addAction(actionSaveAs);
    ui->menuFile->addSeparator();
    ui->menuFile->addAction(ui->actionDelete);

    // Document signals -> window title
    connect(m_pDocument, &Document::modifiedChanged, this, [this]() { updateWindowTitle(); });
    connect(m_pDocument, &Document::filePathChanged, this, [this](const QString &) { updateWindowTitle(); });
    updateWindowTitle();
}

void CMainWindow::onAction_zoomIn()
{
    m_pDrawingPanel->grahpicsViewZoomIn();
}

void CMainWindow::onAction_zoomOut()
{
    m_pDrawingPanel->grahpicsViewZoomOut();
}

void CMainWindow::onAction_zoomFit()
{
    m_pDrawingPanel->grahpicsViewZoomFit();
}

void CMainWindow::onAction_createGroup()
{
    GraphicsItemGroup* group = m_pDrawingPanel->createItemGroup();
    if(group)
    {
        QGraphicsScene* scene = m_pDocument->scene();
        QUndoCommand* createItemGropu = new CreateItemGoupCommand(group, scene);
        m_pDocument->execute(createItemGropu);
    }
}

void CMainWindow::onAction_destroyGroup()
{
    QGraphicsScene* scene = m_pDocument->scene();
    QList<QGraphicsItem*> listItem = scene->selectedItems();
    if(listItem.count() != 1)
        return;

    QGraphicsItem* item = listItem.first();
    if(!item)
        return;

    GraphicsItemGroup *group = dynamic_cast<GraphicsItemGroup*>(item);
    if(group)
    {
        QUndoCommand* destroyItemGropu = new DestroyItemGoupCommand(group, scene);
        m_pDocument->execute(destroyItemGropu);
    }
}

void CMainWindow::onSignal_addItem(QGraphicsItem* item)
{
    if(item)
    {
        QUndoCommand* addItemCommand = new AddItemCommand(item, item->scene());
        m_pDocument->execute(addItemCommand);
    }
}

void CMainWindow::onSignal_deleteItem()
{
    QGraphicsScene* scene = m_pDocument->scene();
    if (scene && scene->selectedItems().isEmpty())
        return;

    QUndoCommand* deleteItemCommand = new DeleteItemCommand(scene);
    m_pDocument->execute(deleteItemCommand);
}

void CMainWindow::onSignal_selectionChanged()
{
    QList<QGraphicsItem*> selectedItems = m_pDocument->scene()->selectedItems();
    if(selectedItems.count() != 1) {
        m_pPropertiesEditorView->setObject(m_pDocument->scene());
        return;
    }
    QGraphicsItem *gitem = selectedItems.first();
    QObject *obj = dynamic_cast<QObject *>(gitem);
    if (obj)
        m_pPropertiesEditorView->setObject(obj);
}

// -- File operations -------------------------------------------------------

bool CMainWindow::maybeSave()
{
    if (!m_pDocument->isModified())
        return true;

    QMessageBox::StandardButton ret = QMessageBox::warning(
        this, tr("PowerDesigner"),
        tr("当前文档已修改，是否保存？"),
        QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);

    switch (ret) {
    case QMessageBox::Save:
        if (m_pDocument->filePath().isEmpty())
            onAction_saveAs();
        else
            m_pDocument->save();
        return !m_pDocument->isModified();
    case QMessageBox::Cancel:
        return false;
    default: // Discard
        break;
    }
    return true;
}

void CMainWindow::updateWindowTitle()
{
    QString title = "PowerDesigner";
    QString path = m_pDocument->filePath();
    if (!path.isEmpty()) {
        title += " - " + QFileInfo(path).fileName();
    } else {
        title += " - " + tr("未命名");
    }
    if (m_pDocument->isModified())
        title += " [*]";
    setWindowTitle(title);
    setWindowModified(m_pDocument->isModified()); // shows macOS dot indicator
}

void CMainWindow::onAction_new()
{
    if (!maybeSave())
        return;
    m_pDocument->clear();
}

void CMainWindow::onAction_open()
{
    if (!maybeSave())
        return;

    QString filePath = QFileDialog::getOpenFileName(
        this, tr("打开文件"), QString(),
        tr("JSON 文件 (*.json);;所有文件 (*)"));

    if (filePath.isEmpty())
        return;

    m_pDocument->load(filePath);
}

void CMainWindow::onAction_save()
{
    if (m_pDocument->filePath().isEmpty())
        onAction_saveAs();
    else
        m_pDocument->save();
}

void CMainWindow::onAction_saveAs()
{
    QString filePath = QFileDialog::getSaveFileName(
        this, tr("另存为"), QString(),
        tr("JSON 文件 (*.json);;所有文件 (*)"));

    if (filePath.isEmpty())
        return;

    m_pDocument->saveAs(filePath);
}
