#include "clipboard.h"
#include "sqlite_orm/sqlite_orm.h"
#include <qlogging.h>

// using sqlite_orm::datetime;
// using sqlite_orm::default_value;
using sqlite_orm::limit;
using sqlite_orm::make_column;
using sqlite_orm::make_storage;
using sqlite_orm::make_table;
using sqlite_orm::order_by;
using sqlite_orm::primary_key;
using sqlite_orm::where;

// 1. 直接定义静态变量
// static decltype(auto) storage = make_storage("./cbh.db", make_table("CBRows", make_column("id", &CBRow::id, primary_key().autoincrement()),
//                                                                     make_column("content", &CBRow::content), make_column("time", &CBRow::time)));

// 2. 先创建类型，再定义智能指针
using StorageT = decltype(make_storage("./cbh.db", make_table("CBRows", make_column("id", &CBRow::id, primary_key().autoincrement()),
                                                              make_column("content", &CBRow::content), make_column("time", &CBRow::time))));
std::unique_ptr<StorageT> storage;

ClipboardMonitor::ClipboardMonitor(QObject *parent) : QObject(parent) {
    // 生成数据库连接
    storage =
        std::make_unique<StorageT>(make_storage("./cbh.db", make_table("CBRows", make_column("id", &CBRow::id, primary_key().autoincrement()),
                                                                       make_column("content", &CBRow::content), make_column("time", &CBRow::time))));
    storage->sync_schema();
    // 获取系统剪贴板
    QClipboard *clipboard = QApplication::clipboard();
    // 连接 dataChanged 信号到自定义的 onClipboardChanged 槽函数
    connect(clipboard, &QClipboard::dataChanged, this, &ClipboardMonitor::onClipboardChanged);
}

ClipboardMonitor::~ClipboardMonitor() {}

void ClipboardMonitor::onClipboardChanged() {
    // 获取剪贴板对象
    QClipboard *clipboard = QApplication::clipboard();
    // 检查是否有文本内容
    if (!clipboard->mimeData()->hasText())
        return;

    QString text = clipboard->text();
    qDebug() << "Clipboard text changed:" << text;
    storage->insert(CBRow{
        -1,
        text.toStdString(),
        storage->select(datetime("now")).front(),
    });
    refreshTableModel();
}

void ClipboardMonitor::refreshTableModel() {
    auto res = storage->get_all<CBRow>(order_by(&CBRow::id).desc(), limit(5));
    // TODO: 数据存入TableModel
    for (auto k : res) {
        qDebug() << k.id;
    }
}
