#include "chatdatabase.h"

#include <QDir>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlDatabase>

#include <ukui-log4qt.h>

#define CREATE_TABLE_RECORD_SQL "create table record(session TEXT, msg_time DATETIME, who text, msg_str TEXT)"

class ChatDatabase::Private
{
public:
    bool is_open;
    QSqlDatabase base;
};

ChatDatabase::ChatDatabase():
    d(std::make_shared<ChatDatabase::Private>())
{
    initBase();
    createTable();
}

ChatDatabase::~ChatDatabase()
{
    if (d->is_open)
        d->base.close();
}

bool ChatDatabase::insertOne(QString session, QDateTime msg_time, QString who, QString msg_str)
{
    if (!d->is_open)
        return false;

//    QSqlQuery sql_query
}

void ChatDatabase::initBase()
{
    d->base = QSqlDatabase::addDatabase("QSQLITE");
    QString config_path = QDir::homePath().append("/.config/kylin-aiassistant");
    if (!QDir().exists(config_path))
        QDir().mkdir(config_path);

    d->base.setDatabaseName(config_path.append("/database.db"));
    d->is_open = d->base.isOpen();
}

void ChatDatabase::createTable()
{
    QSqlQuery sql_query(d->base);
    if (!sql_query.exec(CREATE_TABLE_RECORD_SQL))
    {
        KyInfo() << "create table record error";
    }
}
