#include "DocumentConverter.h"
#include "MarkdownParser.h"
#include "HtmlWriter.h"
#include "FileLogger.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->SetAccessMode(File::AccessMode::Read);
    input->Open();

    MarkdownParser parser;

    auto handle = input->GetInHandle();
    while(handle->good())
    {
        std::string line;
        std::getline(*handle, line);
        parser.ProcessLine(line);
    };
    input->Close();

    auto html_document = parser.GetHtml();
    HtmlWriter writer;
    std::string html_string = writer.ToString(html_document);

    output->SetAccessMode(File::AccessMode::Write);
    output->Open();
    *(output->GetOutHandle()) << html_string;
    output->Close();
}
