#include "pch.h"
#include "log.h"
#include "node_icon.h"
#include "asset.h"
#include "texture.h"

std::map<std::string, glm::vec4> NodeIcon::m_icons;

void NodeIcon::static_init()
{
    // spritesheet maker: https://draeton.github.io/stitches/
    // icons: http://www.famfamfam.com/lab/icons/silk/
    // regex css -> spritesheet.txt: \.([^{]+) {\s+width: (\d+)px;\s+height: (\d+)px;\s+.*: -(\d+)px -(\d+)px;\s+}\s+
    // to: "\1",\2,\3,\4,\5\n
    Asset file;
    if (!(file.open("data/spritesheet.txt") && file.read_all()))
        return;
    char* data = (char*)file.m_data;
    int size = file.m_len;
    static char name[256];
    int x, y, w, h;
    char* s = strtok(data, "\n");
    auto i = strlen(s) + 1;
    while (i < size && sscanf(s, "%s %d %d %d %d", name, &w, &h, &x, &y) == 5)
    {
        m_icons[name] = glm::vec4(x, y, x + w, y + h);
        s = strtok(nullptr, "\n");
        i += strlen(s) + 1;
    }
    file.close();
    TextureManager::load("data/spritesheet.png");
}

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

void NodeIcon::clone_copy(Node* dest) const
{
    NodeImage::clone_copy(dest);
    NodeIcon* n = static_cast<NodeIcon*>(dest);
    n->m_icon_name = m_icon_name;
}

void NodeIcon::create()
{
    m_region = m_icons[m_icon_name];
    m_path = "data/spritesheet.png";
    m_tex_id = const_hash(m_path.c_str());
    m_use_atlas = true;
    NodeImage::create();
    auto tex_sz = TextureManager::get(m_tex_id).size();
    YGNodeStyleSetAspectRatio(y_node, tex_sz.x / tex_sz.y);
}

void NodeIcon::parse_attributes(kAttribute ka, const tinyxml2::XMLAttribute* attr)
{
    NodeImage::parse_attributes(ka, attr);
    switch (ka)
    {
    case kAttribute::Icon:
        m_icon_name = attr->Value();
        break;
    default:
        break;
    }
}
