#include "SvgReader.h"

#include "File.h"
#include "XmlParser.h"
#include "XmlAttribute.h"

#include "SvgShapeElements.h"

#include "FileLogger.h"

std::unique_ptr<SvgDocument> SvgReader::read(const Path& path) const
{
	auto svg_doc = std::make_unique<SvgDocument>();

    File in_file(path);
    auto lines = in_file.readLines();

    XmlParser parser;
    for (const auto& line : lines)
    {
        parser.processLine(line);
    }

    auto xml_doc = parser.getDocument();

    if (xml_doc->getRoot() && xml_doc->getRoot()->getTagName() == "svg")
    {
        onRoot(xml_doc->getRoot(), svg_doc.get());
    }
    return svg_doc;
}

void SvgReader::onRoot(XmlElement* element, SvgDocument* doc) const
{
    for (const auto& attr : element->getAttributes())
    {
        doc->getRoot()->addAttribute(attr.first, attr.second->getValue());
    }

    for (const auto& child : element->getChildren())
    {
        onChild(child.get(), doc->getRoot());
    }
}

void SvgReader::onChild(XmlElement* element, XmlElement* svg_parent) const
{
    std::unique_ptr<XmlElement> new_svg;
    if (element->getTagName() == "circle")
    {
        new_svg = std::make_unique<SvgCircle>();
    }
    else if (element->getTagName() == "ellipse")
    {
        new_svg = std::make_unique<SvgCircle>(SvgCircle::Type::ELLIPSE);
    }
    else if (element->getTagName() == "rect")
    {
        new_svg = std::make_unique<SvgRectangle>();
    }
    else if (element->getTagName() == "path")
    {
        new_svg = std::make_unique<SvgPath>();
    }
    else
    {
        return;
    }

    for (const auto& attr : element->getAttributes())
    {
        new_svg->addAttribute(attr.first, attr.second->getValue());
    }

    for (const auto& child : element->getChildren())
    {
       onChild(child.get(), new_svg.get());
    }
    svg_parent->addChild(std::move(new_svg));
}