#include "opml_item.hpp"
#include "utils.hpp"

void OpmlItem::parse() {
    if (!essentials_only) {
        title = item_node.attribute("title").value();
        if (title.empty()) title = item_node.attribute("text").value();
        SynDomUtils::trim(title);

        description = item_node.attribute("description").value();
        if (description.empty())
            description = item_node.attribute("text").value();
        SynDomUtils::trim(description);

        url = item_node.attribute("htmlUrl").value();
        SynDomUtils::trim(url);

        type = item_node.attribute("type").value();
        SynDomUtils::trim(type);

        language = item_node.attribute("language").value();
        SynDomUtils::trim(language);
    }

    feed_url = item_node.attribute("xmlUrl").value();
    SynDomUtils::trim(feed_url);

    std::string categories_s = item_node.attribute("category").value();
    if (!categories_s.empty()) {
        categories = SynDomUtils::split(categories_s, ',');
    }
    for (auto ac: additional_categories) {
        categories.push_back(ac);
    }
}

std::string OpmlItem::to_json() {
    std::string res = "        {\n"
        "            \"title\": \"" + title + "\",\n"
        "            \"description\": \"" + description + "\",\n"
        "            \"url\": \"" + url + "\",\n"
        "            \"feed_url\": \"" + feed_url + "\",\n"
        "            \"type\": \"" + type + "\",\n"
        "            \"language\": \"" + language + "\",\n"
        "            \"categories\": [\n";
    if (categories.size() > 0) {
        for (auto cat: categories) {
            res += "                \"" + cat + "\",\n";
        }
        res = res.substr(0, res.size()-2) + "\n";
    }
    res += "            ]\n        }";

    return res;
}

std::string OpmlItem::get_text() {
    std::string res = "";
    res = item_node.attribute("text").value();
    SynDomUtils::trim(res);

    return res;
}
