#include "sidebarwidget.h"

SideBarWidget::SideBarWidget(QWidget *parent) : QWidget(parent)
{
    initLayout();
    initSlots();
}

void SideBarWidget::initLayout()
{
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_StyledBackground, true);

    m_mainLayout = new QVBoxLayout;
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);

    m_backButton = new KBorderlessButton(QIcon::fromTheme("ukui-start-symbolic"));

    m_createButton = new QPushButton(QIcon(":/icon/icon/create_dialog.svg"), tr("Create Dialog"));
    m_createButton->setProperty("isImportant", true);

    m_tabBar = new KTabBar(KTabBarStyle::Sliding, this);
    m_tabBar->addTab("Historical Dialogue");
    m_tabBar->addTab("AI Plugin");

    initHistoryWidgetLayout();

    initPluginsWidgetLayout();
    initPluginItem();

    m_stackedWidget = new QStackedWidget(this);
    m_stackedWidget->insertWidget(TABTITLE_DIALOG, m_historyDialog);
    m_stackedWidget->insertWidget(TABTITLE_PLUGIN, m_plugins);
    m_stackedWidget->setCurrentIndex(TABTITLE_DIALOG);

    m_mainLayout->addWidget(m_backButton);
    m_mainLayout->addWidget(m_createButton);
    m_mainLayout->addWidget(m_tabBar);
    m_mainLayout->addWidget(m_stackedWidget);
    this->setLayout(m_mainLayout);
    this->setFocusPolicy(Qt::NoFocus);

    initHistoryDialogItem();

    this->setFixedSize(400, 300);
    this->hide();

    return;
}

void SideBarWidget::initHistoryWidgetLayout()
{
    m_historyDialog = new QWidget();

    m_queryLineEdit = new KSearchLineEdit(m_historyDialog);
    m_dialogListwidget = new QListWidget(m_historyDialog);
    m_editButton = new KBorderButton(QIcon::fromTheme("document-edit-symbolic"), tr("Edit"));

    QVBoxLayout *historyDialogLayout = new QVBoxLayout;
    historyDialogLayout->addWidget(m_queryLineEdit);
    historyDialogLayout->addWidget(m_dialogListwidget);
    historyDialogLayout->addWidget(m_editButton);
    m_historyDialog->setLayout(historyDialogLayout);

    return;
}

void SideBarWidget::initPluginsWidgetLayout()
{
    m_plugins = new QWidget();

    m_pluginListwidget = new QListWidget(m_plugins);

    QVBoxLayout *pluginsLayout = new QVBoxLayout;
    pluginsLayout->addWidget(m_pluginListwidget);;
    m_plugins->setLayout(pluginsLayout);

    return;
}

void SideBarWidget::initSlots()
{
    connect(m_tabBar, SIGNAL(currentChanged(int)), this, SLOT(onTabBarChanged(int)));
    connect(m_createButton, SIGNAL(clicked(bool)), this, SLOT(onCreateButtonClicked()));
    connect(m_backButton, SIGNAL(clicked(bool)), this, SLOT(onBackButtonClicked()));

    connect(m_pluginListwidget, &QListWidget::itemClicked, this, &SideBarWidget::onPluginItemClicked);
    return;

}

void SideBarWidget::onTabBarChanged(int index)
{
    qDebug() << index;
    m_stackedWidget->setCurrentIndex(index);

    return;
}

void SideBarWidget::onCreateButtonClicked()
{
    emit sigCreateButtonClicked();
    return;
}

void SideBarWidget::onBackButtonClicked()
{
    this->hide();
    return;
}

void SideBarWidget::initPluginItem()
{
     // only for test
    QListWidgetItem *item = new QListWidgetItem(QIcon(":/icon/icon/meeting_assistant.svg"), tr("Meeting Assistant"));
    item->setData(CUSTOM_ROLE_PLUGIN, "qrc:/html/html/meeting-detail.html");
    m_pluginListwidget->addItem(item);

    QListWidgetItem *item2 = new QListWidgetItem(QIcon(":/icon/icon/voice_broadcast.svg"), tr("Voice Announcements"));
    item2->setData(CUSTOM_ROLE_PLUGIN, "qrc:/html/html/voice.html");
    m_pluginListwidget->addItem(item2);

    QListWidgetItem *item3= new QListWidgetItem(QIcon(":/icon/icon/voice_broadcast.svg"), tr("Voice Dictation"));
    item3->setData(CUSTOM_ROLE_PLUGIN, "qrc:/html/html/dictation.html");
    m_pluginListwidget->addItem(item3);

    return;
}


void SideBarWidget::initTestItem()
{

#ifdef QT_DEBUG
     // only for test
    QListWidgetItem *item = new QListWidgetItem();
    m_dialogListwidget->addItem(item);

    HistoryItemWidget *widget = new HistoryItemWidget(QPixmap(":/icon/icon/text_dialog.png"), "1111");
    m_dialogListwidget->setItemWidget(item, widget);
    item->setSizeHint(widget->size());

    QListWidgetItem *item1 = new QListWidgetItem();
    m_dialogListwidget->addItem(item1);

    HistoryItemWidget *widget1 = new HistoryItemWidget(QPixmap(":/icon/icon/voice_dialog.png"), "2222");
    m_dialogListwidget->setItemWidget(item1, widget1);
    item1->setSizeHint(widget1->size());
#endif

    return;
}

void SideBarWidget::initSingleDialogItem(const QString &dialogFile)
{
    QFile file(dialogFile);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return;
    }

    QTextStream in(&file);
    QString jsonData = in.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData.toUtf8());
    if (jsonDoc.isNull()) {
        return;
    }

    if (!jsonDoc.isArray()) {
        // 历史对话保存的是一个json字符串，该字符串最外层为数组。
        return;
    }

    // 获取数组第一个元素，key为msg的属性值
    QJsonArray jsonArray = jsonDoc.array();
    QJsonValue firstElement = jsonArray.first();

    if (!firstElement.isObject()) {
        // 数组的每一个元素都为一个对象，包过数组第一个元素。
        return;
    }

    QJsonObject jsonObject = firstElement.toObject();
    QStringList keys = jsonObject.keys();

    if (!keys.contains("msg")) {
        // 每个对象应该包含msg这个属性。
        return;
    }

    QJsonValue value = jsonObject.value("msg");
    qDebug() << value.toString();

    QListWidgetItem *item = new QListWidgetItem();
    m_dialogListwidget->addItem(item);

    HistoryItemWidget *widget = new HistoryItemWidget(QPixmap(":/icon/icon/text_dialog.png"), value.toString());
    m_dialogListwidget->setItemWidget(item, widget);
    item->setSizeHint(widget->size());

    return;

}

void SideBarWidget::initHistoryDialogItem()
{
    QString dialogDir = QDir::homePath() + "/文档/kylin-aiassistant/dialog";

    QDir dataDir(dialogDir);
    if(!dataDir.exists()) {
       return;
    }

    QFileInfoList fileList = dataDir.entryInfoList(QDir::Files);
    for (const QFileInfo &file : fileList) {
        if (file.suffix().toLower() != "json") {
            continue;
        }

        initSingleDialogItem(file.filePath());
        qDebug() << file.absoluteFilePath();
    }

    return;
}

void SideBarWidget::onSaveDialog(QString fileName)
{
    initSingleDialogItem(fileName);
    return;
}

void SideBarWidget::onPluginItemClicked(QListWidgetItem *item)
{
    QString retrievedData = item->data(CUSTOM_ROLE_PLUGIN).toString();
    qDebug() << "Retrieved data:" << retrievedData;

    emit sigPluginItemClicked(retrievedData);
    return;
}
