/*
 * Peony-Qt
 *
 * Copyright (C) 2024, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: yangyanwei <yangyanwei@kylinos.cn>
 *
 */

#include "desktop-window-manager.h"
#include "peony-desktop-application.h"
#include "advanced-desktop-item-model.h"
#include <KWindowSystem>

#include "common.h"
#include "file-info.h"
#include "file-info-job.h"
#include "file-meta-info.h"
#include "global-settings.h"
#include "file-action-controler.h"
#include "global-settings-adapter.h"
#include "background-manager.h"
#include "screen-manager.h"
#include "theme-style.h"

#include "windowmanager/windowmanager.h"
#include "desktop-item-proxy-model.h"
#include "platformwindow.h"

#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickItem>
#include <QScreen>
#include <QQuickView>
#include <QTimer>

static int desktop_window_id = 0;
static DesktopWindowManager *global_instance = nullptr;

DesktopWindowManager *DesktopWindowManager::getInstance()
{
    if (!global_instance) {
        global_instance = new DesktopWindowManager;
    }
    return global_instance;
}

DesktopWindowManager::DesktopWindowManager(QObject *parent) : QObject(parent)
{
//    connect(kdk::WindowManager::self(),&kdk::WindowManager::windowAdded,this,[=](const kdk::WindowId& windowId){
//        if((quint32)getpid() == kdk::WindowManager::getPid(windowId)) {
//            for (auto window : m_bgWindows) {
//               QString title = kdk::WindowManager::getWindowTitle(windowId);
//                QString windowTitle = window->windowTitle();
//                if (title == windowTitle) {
//                    window->setWindowId(windowId);
//                    if (window->screen() == qApp->primaryScreen()) {
//                        kdk::WindowManager::activateWindow(window->getWindowId());
//                    }
//                    break;
//                }
//            }
//        }
//    });
    registerCppTypeToQml();
    m_model = PeonyDesktopApplication::getModel();
    connect(m_model, &AdvancedDesktopItemModel::emitFinish, this, &DesktopWindowManager::initModelFinish);
    connect(m_model, &AdvancedDesktopItemModel::sig_fileCreated, this, &DesktopWindowManager::fileCreated);

    m_desktopAutoLayout = GlobalSettings::getInstance()->getValue(DESKTOP_USE_AUTO_LAYOUT).toBool();
    connect(GlobalSettings::getInstance(), &GlobalSettings::valueChanged, this, [=](const QString &key){
        if (key == DESKTOP_USE_AUTO_LAYOUT) {
            m_desktopAutoLayout = GlobalSettings::getInstance()->getValue(DESKTOP_USE_AUTO_LAYOUT).toBool();
        }
    });
}


DesktopWindowManager::~DesktopWindowManager()
{
    for (auto window : m_views) {
        delete window;
    }
    m_views.clear();
}

void DesktopWindowManager::registerCppTypeToQml()
{
    qmlRegisterType<Peony::AdvancedDesktopItemModel>("org.ukui.desktop", 1, 0, "AdvancedDesktopItemModel");
    qmlRegisterType<Peony::DesktopItemProxyModel>("org.ukui.desktop", 1, 0, "DesktopItemProxyModel");
    qmlRegisterType<FileActionController>("org.ukui.desktop", 1, 0, "FileActionController");
    qmlRegisterType<GlobalSettingsAdapter>("org.ukui.desktop", 1, 0, "GlobalSettingsAdapter");
    qmlRegisterType<ThemeStyle>("org.ukui.desktop", 1, 0, "ThemeStyle");
    qmlRegisterSingletonType(QUrl("qrc:/qml-desktop/EventBus.qml"), "org.ukui.desktop", 1, 0, "EventBus");
}

void DesktopWindowManager::addQmlDesktop(QScreen *screen)
{
    int screenId = SCREEN_MANAGER->getScreenId(screen);
    PlatformWindow *window = new PlatformWindow(screenId, screen);
    qDebug() << "windowid" << screenId;
    SCREEN_MANAGER->addBackgroundWindow(window, screen, screenId);
    connect(this, &DesktopWindowManager::emitFinish, window, &PlatformWindow::loadData);

    initializeWindowView(window);
    setupWindowConnections(window);
    if (m_initMetaInfo)
        window->loadData();
    connect(this, &DesktopWindowManager::setSortType, window, &PlatformWindow::setSortType);
    connect(this, &DesktopWindowManager::setSortOrder, window, &PlatformWindow::setSortOrder);
    connect(this, &DesktopWindowManager::modeChanged, window, &PlatformWindow::updateView);
    connect(SCREEN_MANAGER, &ScreenManager::windowsRelocateRequired, window, &PlatformWindow::updateWindowGeometry);

    if (window) {
        // 将窗口移动到对应屏幕的位置
        window->show();
        if (window->rootObject()) {
            window->rootObject()->setState("Show");
        }
    }
}

void DesktopWindowManager::singleScreenMode()
{
    bool isMainScreenOnlyData = true;
    for (auto window : SCREEN_MANAGER->getBackgroundWindows()) {
        if (!SCREEN_MANAGER->isPrimaryScreen(window->screen())) {
            PlatformWindow *tmpWindow = qobject_cast<PlatformWindow*>(window);
          //  tmpWindow->lower();
            if (0 != tmpWindow->dataCount()) {
                isMainScreenOnlyData = false;
            }
            break;
        }/* else {
            SCREEN_MANAGER->getWindowById(0)->raise();
        }*/
    }
    qDebug() << "Has primary screen data " << isMainScreenOnlyData << "total item:" << m_model->rowCount();
    if (SCREEN_MANAGER->displayMode() == ScreenManager::Extend  && isMainScreenOnlyData) {
        m_model->clearExtendItemPos();
        return;
    }
    m_model->getAllRestoreInfo();
    m_model->saveExtendItemInfo();
    //SCREEN_MANAGER->getWindowById(0)->raise();
    Q_EMIT modeChanged();
}

void DesktopWindowManager::multiscreenMode()
{
    m_model->getAllRestoreInfo();
    m_model->resetExtendItemInfo();

    Q_EMIT modeChanged();
}

void DesktopWindowManager::relocateIconView()
{
    qInfo() << "start relocate icon view";
    //task#74174 更新多屏显示,根据id过滤元素
    int primaryId = SCREEN_MANAGER->getPrimaryScreenId();
    PlatformWindow *primaryWindow = nullptr;

    for (auto window : SCREEN_MANAGER->getBackgroundWindows()) {
        if (SCREEN_MANAGER->isPrimaryScreen(window->screen())) {
            primaryWindow = qobject_cast<PlatformWindow*>(window);
            break;
        }
    }
    qDebug() << "primary screen id:" << primaryId;
    if (primaryWindow) {
        QList<QQuickView*> list = SCREEN_MANAGER->getBackgroundWindows();
        for (int i = 0 ; i < list.count(); i++) {
            PlatformWindow *window = qobject_cast<PlatformWindow*>(list[i]);
            if (window->id() == 0 && window != primaryWindow) {
                m_model->getAllRestoreInfo();
                // 交换ID
                qDebug() << "切换主副屏:" << primaryId;
                window->setId(primaryWindow->id());
                primaryWindow->setId(primaryId);
                window->updateView();
                primaryWindow->updateView();
                return;
            }
        }
    }
}

void DesktopWindowManager::raiseWid()
{
    QTimer::singleShot(2000, this, [=]() {
        kdk::WindowManager::activateWindow(SCREEN_MANAGER->getWindowById(0), nullptr);
        return;
    });
}

void DesktopWindowManager::layoutViewItems()
{
//    for (auto bgWindow : m_bgWindows) {
//        auto view = bgWindow->getIconView();
//        view->layoutItems();
//    }
}

void DesktopWindowManager::initModelFinish()
{
    if (m_initMetaInfo)
        return;

    int mode = SCREEN_MANAGER->displayMode();
    switchDisplayMode(mode);
    relocateIconView();
    m_initMetaInfo = true;
    Q_EMIT emitFinish();
}

void DesktopWindowManager::markCreateFilePos(const QPoint &pos)
{
    //如果当前创建文件的屏幕满了，则找到一个空的屏幕，按照顺序添加
    PlatformWindow *window =qobject_cast<PlatformWindow*>(SCREEN_MANAGER->getWindowAt(pos));
    int screenId = SCREEN_MANAGER->getScreenIdAt(pos);
    QPoint localPos = SCREEN_MANAGER->mapFromGlobal(screenId, pos);
    //鼠标坐标点转化成网格标点；
    QPoint tmpPos = window->getGridPosFromMousePos(localPos);
    if (window->isFull()) {
        QList<QQuickView*> list = SCREEN_MANAGER->getBackgroundWindows();
        for (int i = 0 ; i < list.count(); i++) {
            PlatformWindow *window = qobject_cast<PlatformWindow*>(list[i]);
            if (!window->isFull()) {
                m_markMousePressPos = QPoint(0, 0);
                m_markMousePressId = window->id();
                return;
            }
        }
        m_markMousePressPos = QPoint(0, 0);
        m_markMousePressId = window->id();
    } else {
        m_markMousePressPos = window->checkGridPos(tmpPos);
        m_markMousePressId = window->id();
    }
}

void DesktopWindowManager::createIdAndPos(int *id, QPoint *pos)
{
    if (m_markMousePressPos == QPoint(-1, -1)) {
        PlatformWindow *window =qobject_cast<PlatformWindow*>(SCREEN_MANAGER->getWindowAt(QCursor::pos()));
        bool isFull = window? window->isFull() : true;
        if (!isFull) {
            *id = window->id();
            *pos = window->findNextEmptyGridPos();
            return;
        }

        QList<QQuickView*> list = SCREEN_MANAGER->getBackgroundWindows();
        for (int i = 0 ; i < list.count(); i++) {
            PlatformWindow *emptyPosWindow = qobject_cast<PlatformWindow*>(list[i]);
            isFull = emptyPosWindow? emptyPosWindow->isFull() : true;
            if (!isFull) {
                *id = emptyPosWindow->id();
                *pos = emptyPosWindow->findNextEmptyGridPos();
                return;
            }
        }
        *id = window->id();
        *pos = QPoint(-1, -1);
        return;
    }
    PlatformWindow *window =qobject_cast<PlatformWindow*>(SCREEN_MANAGER->getWindowById(m_markMousePressId));
    *id = m_markMousePressId;
    *pos = m_desktopAutoLayout? window->findNextEmptyGridPos(): m_markMousePressPos;//自动排列的情况下清空位置的记录
    m_markMousePressPos = QPoint(-1, -1);
    m_markMousePressId = 0;
    return;
}

void DesktopWindowManager::fileCreated(int id, const QString &uri)
{
    auto index = m_model->indexFromUri(uri);
    QPoint metaPos = m_model->data(index,PositionRole).toPoint();
    bool isRenaming =  qApp->property("rename").toBool();

    if (isRenaming && metaPos.x() >= 0 && metaPos.x() >= 0) {
        qApp->setProperty("rename", false);
        int screenId = m_model->data(index, ScreenIdRole).toInt();
        Q_EMIT m_model->idChanged(screenId, -1,  uri);
    } else {
        int oldId = m_model->data(index, ScreenIdRole).toInt();
        QPoint currentPos;
        createIdAndPos(&id, &currentPos);
        m_model->setData(index, id, ScreenIdRole);
        m_model->setData(index, currentPos,PositionRole);
        Q_EMIT m_model->idChanged(id, oldId, uri);
    }
}

void DesktopWindowManager::clearAllRestoreInfo()
{
    for (int i = 0; i < m_model->rowCount(); i++) {
        auto index = m_model->index(i, 0);
        m_model->setData(index, QStringList(""), ExceptedPositionRole);
    }
}

void DesktopWindowManager::initializeWithScreens()
{
    for (auto screen : SCREEN_MANAGER->allScreens()) {
        addQmlDesktop(screen);
    }

    connect(SCREEN_MANAGER, &ScreenManager::screenAdded, this, [this](QScreen* screen, int id) {
        this->addQmlDesktop(screen);
    });

    connect(SCREEN_MANAGER, &ScreenManager::primaryScreenChanged, this, &DesktopWindowManager::relocateIconView);

    connect(SCREEN_MANAGER, &ScreenManager::singleScreenModeActivated, this, &DesktopWindowManager::singleScreenMode);
    connect(SCREEN_MANAGER, &ScreenManager::multiScreenModeActivated, this, &DesktopWindowManager::multiscreenMode);
}

void DesktopWindowManager::initializeWindowView(QQuickView* window)
{
    if (!window) return;

    if (m_initMetaInfo) {
        int mode = SCREEN_MANAGER->displayMode();
        switchDisplayMode(mode);
        relocateIconView();
    } else if (window->screen() == SCREEN_MANAGER->primaryScreen()) {
        m_model->refresh();
    }
}

void DesktopWindowManager::setupWindowConnections(QQuickView* window)
{
    if (!window) return;

    QScreen* screen = window->screen();

    connect(SCREEN_MANAGER, &ScreenManager::screenRemoved, this, [=](QScreen* removedScreen, int id) {
        qDebug() << "removedScreen "<<removedScreen<<id;
        if (screen != removedScreen) return;
        int currentMode = SCREEN_MANAGER->displayMode();
        if (currentMode == ScreenManager::Extend) {
            m_model->saveExtendItemInfo(id);
            PlatformWindow *window =qobject_cast<PlatformWindow*>(SCREEN_MANAGER->getWindowById(0));
            window->updateView();
        } else if (SCREEN_MANAGER->screenCount() == ScreenManager::Single) {
            singleScreenMode();
        }
        SCREEN_MANAGER->removeBackgroundWindow(window);
        delete window;
    });


//    connect(window, &DesktopBackgroundWindow::updateWindow, this, [=](const QRect &geometry){
//        int newMode = SCREEN_MANAGER->checkScreenMode(geometry);
//        switchDisplayMode(newMode);
//        window->setWindowGeometry(geometry);
//    });
}

void DesktopWindowManager::switchDisplayMode(int newMode)
{
    int currentMode = SCREEN_MANAGER->displayMode();
        qDebug()<<"8888888888888" <<currentMode<<newMode;
//    if (currentMode == newMode) return;

    QQuickView *primary = SCREEN_MANAGER->getWindowById(0);
    kdk::WindowManager::activateWindow(primary,primary);
    qDebug() << "raise window" <<primary->screen()->name();
    if (newMode == ScreenManager::Extend) {
        multiscreenMode();
    } else {
        singleScreenMode();
    }
}
