#include "parser.hpp"
#include "dbc.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include <memory>

using std::shared_ptr, std::string, nlohmann::json;
namespace fs = std::filesystem;

shared_ptr<SlideDeck> parse_slides(const string& md_file) {
  shared_ptr<SlideDeck> slides = std::make_shared<SlideDeck>();

  dbc::check(fs::exists(md_file), "md file missing");

  auto size = fs::file_size(md_file);
  string line(size, '\0');
  bool started = false;
  json config;

  if(std::ifstream in_file{md_file, std::ios::binary}) {
    while(std::getline(in_file, line)) {
      if(line == "{") {
        string json_data;

        do {
          json_data += line;
        } while (std::getline(in_file, line) && line != "}");

        json_data += "}";

        config = json::parse(json_data);
        std::cout << "JSON: " << config << '\n';
      } else if(line == "===") {
        fmt::println("START");
        started = true;
      } else if(line == "---") {
        fmt::println("START SLIDE");
      } else {
        if(started) {
          string title = line;
          string content;

          while(std::getline(in_file, line) && line != "---") {
            content += line + "\n";
          }

          slides->emplace_back(title, content, config);
          config = json::parse("{}");
        } else {
          fmt::println("JUNK: {}", line);
        }
      }
    }
  }

  return slides;
}
