#include "pch.h"
#include "log.h"
#include "node_dialog_browse.h"
#include "canvas.h"
#include "node_image_texture.h"
#include "asset.h"
#include "node_message_box.h"
#include "node_text.h"
#include "app.h"
#include "legacy_ui_overlay_services.h"

Node* NodeDialogBrowse::clone_instantiate() const
{
    return new NodeDialogBrowse();
}

void NodeDialogBrowse::clone_finalize(Node* dest) const
{
    NodeDialogBrowse* n = static_cast<NodeDialogBrowse*>(dest);
    n->init_controls();
}

void NodeDialogBrowse::init()
{
    init_template_file("data/dialogs/doc-browse.xml", "dialog-browse");
    init_controls();
}

void NodeDialogBrowse::init_controls()
{
    btn_ok = find<NodeButton>("btn-ok");
    btn_cancel = find<NodeButton>("btn-cancel");
    btn_delete = find<NodeButton>("btn-delete");
    btn_delete->on_click = [this](Node*) {
        if (!current)
            return;
        
        auto msgbox = pp::panopainter::make_legacy_overlay_node<NodeMessageBox>(*App::I);
        msgbox->m_title->set_text("Delete Project");
        msgbox->m_message->set_text(("Are you sure you want to delete " + current->m_file_name + "?").c_str());
        const auto overlay = pp::panopainter::open_legacy_overlay_node_with_handle(*this, msgbox);
        if (!overlay)
        {
            return;
        }
        const auto overlay_handle = overlay.value();
        const auto on_confirm = [this, overlay_handle](Node*){
            auto path = current->m_path;
            int idx = container->get_child_index(current);
            container->remove_child(current);
            if (!container->m_children.empty())
            {
                int newidx = std::min<int>(idx, (int)container->m_children.size() - 1);
                auto next = (NodeDialogBrowseItem*)container->get_child_at(newidx);
                current = nullptr;
                next->on_selected(next);
                next->m_selected = true;
            }
            else
            {
                current = nullptr;
                selected_path = "";
                selected_file = "";
                selected_name = "";
            }
            Asset::delete_file(path);
            const auto close_status =
                pp::panopainter::close_legacy_overlay_node(*this, overlay_handle);
            (void)close_status;
        };
        msgbox->btn_ok->on_click = on_confirm;
        msgbox->on_submit = on_confirm;
        msgbox->btn_cancel->on_click = [this, overlay_handle](Node*) {
            const auto close_status =
                pp::panopainter::close_legacy_overlay_node(*this, overlay_handle);
            (void)close_status;
        };
        root()->update();
    };
    container = find<Node>("files-list");
    init_list();
    if (App::I->supports_working_directory_picker())
    {
        btn_path = find<NodeButton>("btn-path");
        btn_path->on_click = [this](Node*) {
            App::I->pick_dir([this](std::string path) {
                LOG("change working path to %s", path.c_str());
                App::I->work_path = path;
                const auto display_path = App::I->format_working_directory_path(path);
                working_path->set_text_format(
                    "Destination dir: %s",
                    display_path.c_str());
                search_paths = { path };
                clear_list();
                init_list();
            });
        };
        working_path = find<NodeText>("path");
        const auto display_path = App::I->format_working_directory_path(App::I->work_path);
        working_path->set_text_format(
            "Working dir: %s",
            display_path.c_str());
    }
//     if (auto* first = (NodeDialogBrowseItem*)container->get_child_at(0))
//     {
//         first->on_selected(first);
//         first->m_selected = true;
//     }
}

void NodeDialogBrowse::clear_list()
{
    container->remove_all_children();
}

void NodeDialogBrowse::init_list()
{
    std::vector<std::tuple<std::string/*file-name*/, std::string/*path*/>> files;
    for (auto sp : search_paths)
    {
        auto items = Asset::list_files(sp, ".*\\.ppi");
        for (const auto& i : items)
        {
            files.push_back({i, sp + '/' + i});
        }
    }
    for (const auto& f : files)
    {
        auto f_name = std::get<0>(f);
        auto f_path = std::get<1>(f);
        Image thumb = Canvas::I->thumbnail_read(f_path);
        if (thumb.width == 0 || thumb.height == 0)
            continue;

        auto node = new NodeDialogBrowseItem;
        node->set_manager(m_manager);
        node->init();
        node->m_text->set_text(f_name.substr(0, f_name.length() - strlen(".ppi")).c_str());
        node->m_path = f_path;
        node->m_file_name = f_name;
        node->on_selected = [&](NodeDialogBrowseItem* target) {
            if (target == current)
                return;
            selected_path = target->m_path;
            selected_file = target->m_file_name;
            selected_name = selected_file.substr(0, selected_file.length() - strlen(".ppi"));
            if (current)
                current->m_selected = false;
            current = target;
        };

        // load thumb
        if (auto image_tex = node->find<NodeImageTexture>("thumb-tex"))
        {
            image_tex->tex = std::make_shared<Texture2D>();
            image_tex->tex->create(thumb);
        }
        container->add_child(node);
    }

}

bool NodeDialogBrowse::is_selected()
{
    return current != nullptr;
}

void NodeDialogBrowse::loaded()
{
}

//////////////////////////////////////////////////////////////////

Node* NodeDialogBrowseItem::clone_instantiate() const
{
    return new NodeDialogBrowseItem;
}
void NodeDialogBrowseItem::clone_finalize(Node* dest) const
{
    NodeDialogBrowseItem* n = static_cast<NodeDialogBrowseItem*>(dest);
    n->init_controls();
}
void NodeDialogBrowseItem::init()
{
    init_template_file("data/dialogs/doc-browse.xml", "dialog-browse-item");
    init_controls();
}
void NodeDialogBrowseItem::init_controls()
{
    m_text = find<NodeText>("title");
    m_thumb = find<NodeImageTexture>("thumb-tex");
}
void NodeDialogBrowseItem::loaded()
{

}
void NodeDialogBrowseItem::draw()
{
    auto c = m_selected ? m_color_selected : m_color_normal;
    m_thinkness = m_selected ? 1.f : 0.f;
    m_color = m_mouse_inside ? m_color_hover : c;
    NodeBorder::draw();
}
kEventResult NodeDialogBrowseItem::handle_event(Event* e)
{
    NodeBorder::handle_event(e);
    switch (e->m_type)
    {
    case kEventType::MouseEnter:
        break;
    case kEventType::MouseLeave:
        break;
    case kEventType::MouseDownL:
        m_selected = true;
        if (on_selected)
            on_selected(this);
        break;
    case kEventType::MouseUpL:
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Consumed;
}
