#include "DocumentConverter.h"

#include "MarkdownParser.h"
#include "MarkdownDocument.h"
#include "MarkdownConverter.h"
#include "MarkdownElement.h"

#include "HtmlDocument.h"
#include "HtmlWriter.h"

#include "FileLogger.h"
#include "File.h"

#include <fstream>

DocumentConverter::DocumentConverter()
{

}

void DocumentConverter::convert(File* input, File* output)
{
    if(!input || !output)
    {
        return;
    }

    const auto input_format = input->inferFormat();
    switch (input_format)
    {
        case FileFormat::Format::Markdown:
        {
            convertMarkdown(input, output);
            break;
        }
        default:
        {
            break;
        }
    }
}

void DocumentConverter::convertMarkdown(File* input, File* output)
{
    const auto output_format = output->inferFormat();
    switch (output_format)
    {
        case FileFormat::Format::Html:
        {
            markdownToHtml(input, output);
            break;
        }
        default:
        {
            break;
        }
    }
}

void DocumentConverter::markdownToHtml(File* input, File* output)
{
    MLOG_INFO("Converting Markdown to Html");
    input->open(File::AccessMode::Read);

    MarkdownParser parser;
    auto md_doc = parser.run(input->readText());
    input->close();

    MarkdownConverter converter;
    auto html_doc = converter.convert(md_doc.get());

    HtmlWriter writer;
    std::string html_string = writer.toString(html_doc.get());

    output->open(File::AccessMode::Write);
    *(output->getOutHandle()) << html_string;
    output->close();
}
