#include "pch.h"
#include "log.h"
#include "node_dialog_export_ppbr.h"
#include "app.h"
#include "image.h"

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

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

void NodeDialogExportPPBR::init()
{
    init_template_file("data/dialogs/brush-export.xml", "dialog-brush-upload");
    init_controls();
    m_capture_children = false; // don't capture children events on mouse_capture
}

void NodeDialogExportPPBR::init_controls()
{
    m_title = find<NodeText>("title");
    m_dest_path_txt = find<NodeText>("dest-path");
    if (m_dest_path_txt)
        m_dest_path_txt->SetVisibility(false);
    btn_ok = find<NodeButton>("btn-ok");
    btn_cancel = find<NodeButton>("btn-cancel");
    btn_header_open = find<NodeButton>("header-open");
    btn_header_open->on_click = [this] (Node*) {
        open_header();
    };
    btn_header_clear = find<NodeButton>("header-clear");
    btn_header_clear->on_click = [this] (Node*) {
        m_header_image.reset();
        img_header->tex.reset();
        txt_header_descr->SetVisibility(true);
    };
    btn_header_gen = find<NodeButton>("header-gen");
    btn_header_gen->on_click = [this] (Node*) {
        App::I->message_box("WIP", "This feature is not yet implemented.");
    };
    btn_pick_dest = find<NodeButton>("pick-dest");
    if (btn_pick_dest)
    {
        btn_pick_dest->on_click = [this] (Node*) {
            App::I->pick_dir([this](std::string path){
                m_dest_path = path;
                m_dest_path_txt->set_text(("Dest: " + path).c_str());
                m_dest_path_txt->SetVisibility(true);
                export_check->set_value(true);
            });
        };
    }
    img_header = find<NodeImageTexture>("header-tex");
    txt_header_descr = find<NodeText>("header-descr");
    txt_author = find<NodeTextInput>("info-author");
    txt_email = find<NodeTextInput>("info-email");
    txt_url = find<NodeTextInput>("info-url");
    txt_descr = find<NodeTextInput>("info-descr");
    export_check = find<NodeCheckBox>("export-data");
}

void NodeDialogExportPPBR::open_header()
{
    App::I->pick_image([this](std::string path) {
        m_header_image = std::make_shared<Image>();
        m_header_image->load(path);
        m_header_image->resize(256, 128);
        img_header->tex = std::make_shared<Texture2D>();
        img_header->tex->create(*m_header_image);
        txt_header_descr->SetVisibility(false);
    });
}

void NodeDialogExportPPBR::added(Node* parent)
{
    NodeBorder::added(parent);
    if (added_to_root())
        mouse_capture();
    txt_author->key_capture();
}
