#include "viewfilterfiles.h"
#include "ui_viewfilterfiles.h"
#include "mainwindow.h"
#include "src/frame/signals.h"
#include "src/frame/xatom-helper.h"
#include "src/frame/logger.h"
#include "src/frame/configuration.h"
#include "src/po/translation.h"
#include "src/model/logicmain.h"
#include "src/data/datadirectory.h"
#include "src/view/burndata.h"
#include "src/view/filefilterrules.h"
#include <ukuistylehelper.h>
#include <QDebug>
#include <windowmanager.h>
#include <QDesktopWidget>
using namespace kdk;

ViewFilterFiles *ViewFilterFiles::m_oInstance = nullptr;
QMutex           ViewFilterFiles::m_oMutex;

ViewFilterFiles::ViewFilterFiles(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ViewFilterFiles),
    m_oModel(new FileFilterModel(this))
{
    QFont f;
    qreal basic;
    ui->setupUi(this);

    //判断是否是wayland环境
    if(QString(qgetenv("XDG_SESSION_TYPE")) == "wayland") {
        m_bIsWayland = true;
    } else {
        m_bIsWayland = false;
        MotifWmHints hints;
        hints.flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
        hints.functions = MWM_FUNC_ALL;
        hints.decorations = MWM_DECOR_BORDER;
        XAtomHelper::getInstance()->setWindowMotifHint(winId(), hints);
    }
    ui->title->onlyShowInDialog();
    connect(ui->title, SIGNAL(close()), this, SLOT(close()));
    connect(this, SIGNAL(windowIconChanged(QIcon)), ui->title, SLOT(onWindowIconChange(QIcon)));
    connect(this, SIGNAL(windowTitleChanged(QString)), ui->title, SLOT(onWindowTitleChange(QString)));
    setWindowIcon(QIcon::fromTheme("burner"));
    //setWindowTitle(_("KylinBurner") + " - " + _("ViewFilterFile(s)"));
    setWindowTitle(_("KylinBurner"));
    connect(g_user_signal, &GlobalUserSignal::iconChange, [=](QIcon icon){
        setWindowIcon(icon);
    });
    f = ui->labelTitle->font();
    f.setPixelSize(16);
    f.setBold(true);
    ui->labelTitle->setFont(f);
    ui->labelTitle->setText(_("ViewFilterFile(s)"));

    f = ui->btnRecovery->font();
    f.setPixelSize(14);
    //f.setUnderline(true);
    ui->btnSetting->setFont(f);
    ui->btnSetting->setText(_("Rules"));
    ui->btnRecovery->setFont(f);
    ui->btnRecovery->setText(_("Recovery all"));

    ui->comboBox->setFont(f);

    ui->treeView->setModel(m_oModel);
    ui->treeView->setFont(f);
	ui->treeView->setAlternatingRowColors(true);
    ui->treeView->header()->setFixedHeight(28);
    ui->treeView->header()->setAutoFillBackground(true);
    m_oModel->setHeaderData(0, Qt::Horizontal, _("FileName"), Qt::DisplayRole);
    m_oModel->setHeaderData(1, Qt::Horizontal, _("FilePath"), Qt::DisplayRole);
    m_oModel->setHeaderData(2, Qt::Horizontal, _("FileTime"), Qt::DisplayRole);
    ui->treeView->sortByColumn(2);
    ui->treeView->header()->setSectionHidden(2, true);
    ui->treeView->header()->setStyleSheet("QHeaderView::section{border: 0px solid white;}");
    ui->treeView->setSelectionMode(QTreeView::ExtendedSelection);
    ui->treeView->setItemsExpandable(false);
    ui->treeView->setContextMenuPolicy(Qt::ActionsContextMenu);

    basic = width() / 10;
    ui->treeView->header()->setSectionResizeMode(QHeaderView::Fixed);
    ui->treeView->header()->resizeSection(0, basic * 4);
    ui->treeView->header()->resizeSection(1, basic * 5);

    connect(ui->btnRecovery, SIGNAL(clicked(bool)), this, SLOT(slotsRecovery()));
    connect(ui->treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(slotsSelectionChanged()));
    connect(ui->btnSetting, SIGNAL(clicked(bool)), m_oModel, SLOT(showRules()));
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(updateIndex(int)));
    connect(this, SIGNAL(delNode(int)), this, SLOT(deleteNode(int)));
    connect(m_oModel, &FileFilterModel::node, [=](QIcon icon, QString dis){
        ui->comboBox->addItem(icon, dis);
    });
    connect(m_oModel, &FileFilterModel::root, [=](QModelIndex idx){
        ui->treeView->setRootIndex(idx);
    });
    connect(m_oModel, SIGNAL(recovery(QList<void*>,QList<void*>,QList<void*>)),
            this, SIGNAL(recovery(QList<void*>,QList<void*>,QList<void*>)));

    ui->horizontalLayout->setStretch(0,1);
    ui->horizontalLayout->setContentsMargins(24,11,24,24);
}

ViewFilterFiles *ViewFilterFiles::instance()
{
    if (nullptr == m_oInstance)
    {
        QMutexLocker locker(&m_oMutex);
        if (nullptr == m_oInstance)
        {
            m_oInstance = new ViewFilterFiles();
        }
    }
    return m_oInstance;
}

bool ViewFilterFiles::filtered()
{
    return m_oModel->filtered() > 0;
}

int ViewFilterFiles::currentIndex()
{
    return ui->comboBox->currentIndex();
}

QList<void *> ViewFilterFiles::recoveryHiddenData(int idx, int level)
{
    if (level < 0) level = 0;
    return m_oModel->recoveryHiddenData(idx, level);
}

QList<void *> ViewFilterFiles::recoveryBrokenData(int idx, int level)
{
    if (level < 0) level = 0;
    return m_oModel->recoveryBrokenData(idx, level);
}

QList<void *> ViewFilterFiles::recoveryRepleaceData(int idx, int level)
{
    if (level < 0) level = 0;
    return m_oModel->recoveryRepleaceData(idx, level);
}

void ViewFilterFiles::updatePosition(QPoint p)
{
    m_oPosition.setX(p.x() - width() / 2);
    m_oPosition.setY(p.y() - height() / 2);
}

void ViewFilterFiles::show()
{
    int idx;

    idx = ui->comboBox->currentIndex();
    if (idx >= 0) updateIndex(idx);

//    move(m_oPosition);
    if(m_bIsWayland){
        kdk::UkuiStyleHelper::self()->removeHeader(this);
    }else{
        QPoint position = MainWindow::Instance()->frameGeometry().topLeft();
        move(position.x()+(MainWindow::Instance()->width()-width())/2, position.y()+(MainWindow::Instance()->height()-height())/2);
        kdk::WindowManager::setGeometry(windowHandle(),geometry());
    }
    QDialog::exec();
}

void ViewFilterFiles::newFilterRoot(void *d)
{
    m_oModel->addFilterNode(d);
}

void ViewFilterFiles::filterHidden(int idx, void *data)
{
    m_oModel->addFilterData(idx, data);
    update();
}

void ViewFilterFiles::filterBroken(int idx, void *data)
{
    m_oModel->addFilterData(idx, data);
    update();
}

void ViewFilterFiles::repleace(int idx, void *data)
{
    m_oModel->addFilterData(idx, data);
    update();
}

void ViewFilterFiles::updateIndex(int idx)
{
    m_oModel->updateIndex(idx);
    if (!(FILTERRULES->isHidden())) m_oModel->showRules();
    check();
}

void ViewFilterFiles::deleteNode(int idx)
{
    ui->comboBox->removeItem(idx);
    m_oModel->deleteFilterNode(idx);
}

void ViewFilterFiles::slotsSelectionChanged()
{
    check();
#if 0
    if (0 == ui->treeView->selectionModel()->selectedRows().size())
    {
        ui->btnRecovery->setText(_("Recovery all"));
    }
    else
    {
        ui->btnRecovery->setText(_("Recovery selected"));
    }
#endif
}

void ViewFilterFiles::slotsRecovery()
{
    qDebug()<<__LINE__<<__func__<<"恢复所有";

    m_oModel->recovery(/* ui->treeView->selectionModel()->selectedRows(0) */);
}

void ViewFilterFiles::check()
{
    DataDirectory *root;

    root = static_cast<DataDirectory *>(ui->treeView->rootIndex().internalPointer());
    if (nullptr == root) return;
    if (root->count() == 0)
        ui->btnRecovery->setEnabled(false);
    else
        ui->btnRecovery->setEnabled(true);
}

void ViewFilterFiles::paintEvent(QPaintEvent *event)
{
    QPalette pal = palette();
    if ("ukui-black" == MAIN->theme())
        pal.setBrush(QPalette::Background, QColor("#1D1D1D"));
    else
        pal.setBrush(QPalette::Background, QColor("#FFFFFF"));
    setPalette(pal);
    QDialog::paintEvent(event);
}

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