#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_all.hpp>

#include <language/utils/OFStream.hpp>
#include <utils/Messenger.hpp>
#include <utils/Stringify.hpp>

#include <filesystem>

// clazy:excludeall=non-pod-global-static

TEST_CASE("OFStream", "[language]")
{
  SECTION("ofstream")
  {
    const std::string basename =
      std::filesystem::path{PUGS_BINARY_DIR}.append("tests").append("ofstream_dir").append("ofstream_");
    const std::string filename = basename + stringify(parallel::rank());

    // Ensures that the file is closed after this line
    std::make_shared<OFStream>(filename) << "foo" << 3 << " bar\n";

    if (parallel::rank() == 0) {
      REQUIRE(std::filesystem::is_regular_file(filename));

      std::ifstream is(filename);

      char file_content[10];
      for (size_t i = 0; i < 10; ++i) {
        char c = is.get();

        file_content[i] = c;
        if (c == '\n') {
          file_content[i + 1] = '\0';
          REQUIRE(i == 8);

          c = is.get();
          REQUIRE(is.eof());
          break;
        }
      }

      std::string content = file_content;
      REQUIRE(content == "foo3 bar\n");

      std::filesystem::remove(filename);
    }

    REQUIRE(not std::filesystem::exists(filename));
  }

  SECTION("bad filename")
  {
    if (parallel::rank() == 0) {
      REQUIRE_THROWS_WITH(OFStream{"/"}, "error: cannot create file /");
    }
  }
}