/*
 *
 *  * Copyright (C) 2023, 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: Nicole <buxiaoqing@kylinos.cn>
 *  *          Zhang <zhangyuanyuan1@kylinos.cn>
 *
 */

#include "windowThumbnailManager.h"
#include "../panel/iukuipanel.h"
#include "../panel/common/common.h"
#include <QScreen>
#include <QX11Info>

WindowThumbnailManager::WindowThumbnailManager(QObject *parent)
{
    m_view = new ThumbnailView();
    connect(m_view, &ThumbnailView::viewModelChanged, this, [=]() {
        m_view->setViewPosition(m_panelPosition, m_panelSize, m_x, m_y);
    });

    connect(kdk::WindowManager::self(), &WindowManager::currentDesktopChanged, this, [&](){
        hide("");
    });
}

WindowThumbnailManager::~WindowThumbnailManager()
{
    if (m_view != nullptr) {
        delete m_view;
        m_view = nullptr;
    }
}

void WindowThumbnailManager::show(QList<WindowId> winIdList, QString groupName, int x, int y)
{
    m_winIdList = winIdList;
    m_groupName = groupName;
    m_x = x;
    m_y = y;

    //get position and size of panel
    const QByteArray id(PANEL_SETTINGS);
    if (QGSettings::isSchemaInstalled(id)) {
        QGSettings *gsettings = new QGSettings(id, QByteArray(), this);
        m_panelPosition = (PanelPositionType)gsettings->get(PANEL_POSITION_KEY).toInt();
        m_panelSize = gsettings->get(PANEL_SIZE_KEY).toInt();
    }

    ThumbnailModel::instance()->clear();
    ThumbnailModel::instance()->setModelData(winIdList, groupName);

    m_view->setShowHorizontalView(isHorizontalPanel());
    m_view->setViewModel(winIdList);
    m_view->setViewPosition(m_panelPosition, m_panelSize, m_x, m_y);
    m_view->requestActivate();
    m_view->setViewVisible(true);
}

void WindowThumbnailManager::hide(QString groupName)
{
    Q_UNUSED(groupName);
    if (!m_view->geometry().contains(QCursor::pos())) {
        m_view->setViewVisible(false);
    }
}

bool WindowThumbnailManager::isHorizontalPanel()
{
    return m_panelPosition == PanelPositionType::Bottom || m_panelPosition == PanelPositionType::Top;
}
