#include "pch.h"
#include "log.h"
#include "node_remote_page.h"
#include "node_button.h"
#include "node_scroll.h"
#include "asset.h"
#include "node_text.h"
#include "node_metadata.h"
#include "legacy_ui_overlay_services.h"

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

void NodeRemotePage::clone_copy(Node* dest) const
{
    auto n = static_cast<NodeRemotePage*>(dest);
    n->m_page_id = m_page_id;
    n->m_loaded = m_loaded;
}

void NodeRemotePage::init()
{
    init_template_file("data/dialogs/remote-page.xml", "remote-page");
    init_controls();
}

void NodeRemotePage::init_controls()
{
    m_content = find<NodeScroll>("content");
    m_title = find<NodeText>("title");
}

std::future<bool> NodeRemotePage::load_url(const std::string& url, 
    std::function<void(bool success)> on_complete /*= nullptr*/) noexcept
{
    m_loading = true;

    auto align = m_content->add_child_ref<Node>();
    align->SetWidthP(100.f);
    align->SetHeightP(100.f);
    align->SetAlign(YGAlignCenter);
    align->SetJustify(YGJustifyCenter);
    auto text = align->add_child_ref<NodeText>();
    text->set_font_size(30);
    text->set_text("Connecting to the server...");

    m_url = url;
    m_loaded = false;
    auto remote = std::make_shared<Asset>();
    auto prom = std::make_shared<std::promise<bool>>();
    remote->open_url_async(url, nullptr, [this, remote, align, text, prom, on_complete](bool success) {
        if (success)
        {
            m_content->add_child_xml(std::string((char*)remote->m_data, (size_t)remote->m_len), "about");
            if (auto meta = m_content->find<NodeMetadata>("metadata"))
                m_page_id = std::stol(meta->m_props["page-id"]);
            pp::panopainter::destroy_legacy_node(*align);
        }
        else
        {
            text->set_text("Error loading the page");
        }
        m_loaded = success;
        m_loading = false;
        prom->set_value(success);
        if (on_complete)
            on_complete(success);
    });
    return prom->get_future();
}

void NodeRemotePage::reload() noexcept
{
    if (m_loading)
        return;
    m_content->remove_all_children();
    load_url(m_url);
}

void NodeRemotePage::set_title(const std::string& title)
{
    m_title->set_text(title);
}

void NodeRemotePage::add_button(const std::string& label, int width,
    std::function<void(Node* target)> onclic /*= nullptr*/) noexcept
{
    if (auto footer = find("footer"))
    {
        auto b = footer->add_child<NodeButton>();
        b->m_text->set_text(label);
        b->m_border->SetWidth(width);
        b->m_border->SetHeight(30);
        b->m_border->SetMargin(5, 0, 0, 0);
        b->on_click = onclic;
    }
}
