#include "wnd_hierachy.h"

#include <render_type_def.h>
#include <qevent.h>
#include <QVBoxLayout>
#include <QScrollArea>
#include <QLabel>
#include <QMimeData>
#include "resource.h"
#include <tool.h>
#include <render/task.h>
#include <iostream>
#include <QMessageBox>

#include "wgt_listitem.h"
#include "states.h"
#include <mutex>

namespace {

std::mutex mtx_cb{};
std::condition_variable cv_cb{};
Z::ResultMessage g_CallbackMessage{};
void CallBack_WakeThreadUp(Z::ResultMessage msg) { // 被Renderer回调
    g_CallbackMessage = msg;
    cv_cb.notify_all();
}
void WaitForResult() {
    std::unique_lock lk(mtx_cb);
    cv_cb.wait(lk);
}


void OnItemClicked(ListItemWidget *item) {
    item->SetSelected(true);
    EVENT::InspecItem it{};
    it.type = RenderObj;
    std::memcpy(&it.resource, &item->m_data, 8);
    EVENT::OnSelectItem.EmitEvent(it);

}

}

//=public
WndHierachy::WndHierachy(QWidget *parent) : QWidget(parent) {
    setAttribute(Qt::WA_StyledBackground, true);
    setAcceptDrops(true);
    setLayout(new QVBoxLayout());


    ShowPanel();
}

//=protected
void WndHierachy::dragEnterEvent(QDragEnterEvent *event) {
    if (event->mimeData()->hasFormat("application/x-model")) {
        event->acceptProposedAction(); // 接受：后续才会有 dragMove/drop/leave
        event->accept();
    } else {
        event->ignore();
    }
}

void WndHierachy::dropEvent(QDropEvent *event) {
    event->accept();
    QByteArray baa{event->mimeData()->data("application/x-model")};
    const char *str = baa.data();
    std::string path_str{str};
    std::filesystem::path path{std::u8string(reinterpret_cast<const char8_t *>(path_str.c_str()), path_str.size())};
    Z::Model *model = LoadedResource::GetLoadedModel(path);
    if (model == nullptr) {
        MessageBoxW(nullptr, Z::u8_to_wstring(path_str).c_str(),
                    L"未加载模型",MB_OK);
        return;
    }
    // 向 GRAPHIC 添加渲染
    Z::Task t{};
    t.type = Z::CmdType::AddRenderObj;
    t.cmd.add_render_obj.model = model;
    t.fpCallBack = CallBack_WakeThreadUp;
    Z::Task::AddCommand(t);
    WaitForResult();
    if (g_CallbackMessage.res != Z::ResultType::OK) {
        return;
    }
    int id{-2};

    // 返回的 .data 是 Graphic里的RenderObj的ID
    std::memcpy(&id, g_CallbackMessage.data, sizeof(int));
    // 创建 render object 由此窗口管理
    std::u8string u8objname{path.stem().u8string()};
    RENDEROBJ::Object *obj = new RENDEROBJ::Object{
        std::string{reinterpret_cast<const char *>(u8objname.c_str()), u8objname.size()}, id};
    obj->m_mats.resize(model->ar_meshDatas.size(), nullptr);

    m_lstItems.push_back(obj);

    ShowPanel();
}


//=private
void WndHierachy::ShowPanel() {
    if (m_scroll) {
        layout()->removeWidget(m_scroll);
        m_scroll->deleteLater();
    };

    m_scroll = new QScrollArea{};
    layout()->addWidget(m_scroll);

    QWidget *content = new QWidget(m_scroll);
    QVBoxLayout *layout = new QVBoxLayout{content};
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);

    SelectedItemWidgetGroup *group = SelectedItemWidgetGroup::GetGroup("inspector");

    for (auto item: m_lstItems) {
        QLabel *lb = new QLabel{item->name.c_str()};
        ListItemWidget *w = new ListItemWidget{lb, this, group};
        w->SetMime("application/x-renderobj-id", std::to_string(item->id).c_str());
        std::memcpy(&w->m_data, &item, 8);
        connect(w, &ListItemWidget::Clicked, this, OnItemClicked);
        layout->addWidget(w);
    }

    layout->addStretch();

    m_scroll->setWidget(content);
    m_scroll->setWidgetResizable(true);
}












//
