#include "SvgDocument.h"

#include "XmlAttribute.h"
#include "StringUtils.h"

#include <sstream>

SvgDocument::SvgDocument()
    : XmlDocument()
{
    auto root = XmlElement::Create("svg");

    auto xmlns = std::make_unique<XmlAttribute>("xmlns");
    xmlns->setValue("http://www.w3.org/2000/svg");

    root->addAttribute(std::move(xmlns));

    setRoot(std::move(root));
}

void SvgDocument::setViewBox(double x, double y, double w, double h)
{
    std::stringstream sstr;
    sstr << x << " " << y << " " << w << " " << h;
    setViewBox(sstr.str());
}

void SvgDocument::setViewBox(const std::string& data)
{
    auto viewbox = std::make_unique<XmlAttribute>("viewBox");
    viewbox->setValue(data);
    getRoot()->addAttribute(std::move(viewbox));
}

SvgDocument::ViewBox SvgDocument::getViewBox() const
{
    ViewBox viewBox;

    if (!getRoot())
    {
        return viewBox;
    }

    if (auto vb_attr = getRoot()->getAttribute("viewBox"); vb_attr)
    {
        auto entries = StringUtils::split(vb_attr->getValue());
        if (entries.size() != 4)
        {
            return viewBox;
        }

        viewBox.mX = std::stod(entries[0]);
        viewBox.mY = std::stod(entries[1]);
        viewBox.mW = std::stod(entries[2]);
        viewBox.mH = std::stod(entries[3]);
    }
    return viewBox;
}
