/*
 * 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 "desktop-menu-plugin-manager.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();
    initPeonyDbusService();
    m_model = PeonyDesktopApplication::getModel();
    connect(m_model, &AdvancedDesktopItemModel::emitFinish, this, &DesktopWindowManager::initModelFinish);
    connect(m_model, &AdvancedDesktopItemModel::sig_fileCreated, this, &DesktopWindowManager::fileCreated);
    connect(m_model, &AdvancedDesktopItemModel::setInfoPos, this, &DesktopWindowManager::setInfoPos);

    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()
{
    if (m_peonyDbusService) {
        delete m_peonyDbusService;
        m_peonyDbusService = nullptr;
    }
}

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");
}

void DesktopWindowManager::addQmlDesktop(QScreen *screen)
{
    static bool pluginLoad = false;
    int screenId = SCREEN_MANAGER->getScreenId(screen);
    PlatformWindow *window = new PlatformWindow(screenId, screen);
    if (!pluginLoad) {
        connect(window, &PlatformWindow::viewUpdated, DesktopMenuPluginManager::getInstance(), &DesktopMenuPluginManager::loadAsync);
        pluginLoad = true;
    }
    qDebug() << "windowid" << screenId;
    SCREEN_MANAGER->addBackgroundWindow(window, screen, screenId);
    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);
    connect(this, &DesktopWindowManager::emitFinish, window, &PlatformWindow::loadData);

    window->show();
    initializeWindowView(window);
    setupWindowConnections(window);

    if (m_initMetaInfo)
        window->loadData();
}

void DesktopWindowManager::singleScreenMode()
{
    bool isMainScreenOnlyData = true;
    for (auto window : SCREEN_MANAGER->getBackgroundWindows()) {
        PlatformWindow *tmpWindow = qobject_cast<PlatformWindow*>(window);
        if (!SCREEN_MANAGER->isPrimaryScreen(tmpWindow->bindScreen())) {
          //  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();
    Q_EMIT modeChanged();
}

void DesktopWindowManager::multiscreenMode()
{
    qDebug() <<"change multiscreen: backgroundwindows count:" <<SCREEN_MANAGER->getBackgroundWindows().count()<<" screen count:"<<SCREEN_MANAGER->allScreens().count();
    if (SCREEN_MANAGER->getBackgroundWindows().count() != SCREEN_MANAGER->allScreens().count()) {
        return;
    }
    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()) {
        PlatformWindow *tmpWindow = qobject_cast<PlatformWindow*>(window);
        if (SCREEN_MANAGER->isPrimaryScreen(tmpWindow->bindScreen())) {
            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();
                break;
            }
        }
        QTimer::singleShot(100, primaryWindow, [=]() {
             primaryWindow->requestActivate();
        });
    }
}

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);
    if (QGuiApplication::layoutDirection() == Qt::RightToLeft) {
        int newLocalX = SCREEN_MANAGER->getScreenSize(screenId).isValid()? SCREEN_MANAGER->getScreenSize(screenId).width() - localPos.x() : localPos.x();
        localPos.setX(newLocalX);
    }
    //鼠标坐标点转化成网格标点；
    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::setInfoPos(const QString &uri)
{
    auto info = FileInfo::fromUri(uri);
    QPoint currentPos;
    int id;
    createIdAndPos(&id, &currentPos);
    info->setProperty("createId", id);
    info->setProperty("createPos", currentPos);
    qDebug() << "Make the coordinate points of the newly creted file : "<<id<<currentPos ;
}

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() && metaPos.x() >= 0 && metaPos.x() >= 0;
    if (isRenaming) {
        qApp->setProperty("rename", false);
    }

    bool isHidden = false;
    auto info = FileInfo::fromUri(uri);
    if (!GlobalSettings::getInstance()->getValue(SHOW_HIDDEN_PREFERENCE).toBool()) {
        auto metainfo = FileMetaInfo::fromUri(uri);
        if (metainfo->hasHiddenInfo()) {
            isHidden = metainfo->isHidden();
        } else {
            isHidden = info->isHiddenFile();
        }
    }

    if (isHidden) return;

    if (isRenaming) {
        int screenId = m_model->data(index, ScreenIdRole).toInt();
        Q_EMIT m_model->idChanged(screenId, -1,  QStringList(uri));
    } else {
        int oldId = m_model->data(index, ScreenIdRole).toInt();
        id = SCREEN_MANAGER->displayMode() == ScreenManager::Mirror? 0 : id;
        m_model->setData(index, id, ScreenIdRole);
        Q_EMIT m_model->idChanged(id, oldId, QStringList(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 = qobject_cast<PlatformWindow*>(window)->bindScreen();

    connect(SCREEN_MANAGER, &ScreenManager::screenRemoved, window, [=](QScreen* removedScreen, int id) {
        qDebug() << "removedScreen "<<id<<"primay screen geometry:"<<SCREEN_MANAGER->primaryScreen()->geometry();
        if (screen != removedScreen) return;
        //SCREEN_MANAGER会发送显示模式切换信号
        PlatformWindow *p =qobject_cast<PlatformWindow*>(window);
        p->destoryScreen();

        window->disconnect();
        SCREEN_MANAGER->removeBackgroundWindow(window);
        delete window;
    });
}

void DesktopWindowManager::initPeonyDbusService()
{
    m_peonyDbusService = new PeonyDbusService;
    m_peonyDbusService->DbusServerRegister();
}

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

    QQuickView *primary = SCREEN_MANAGER->getWindowById(0);
    if (newMode == ScreenManager::Extend) {
        multiscreenMode();
    } else {
        singleScreenMode();
    }
}
