#include "catch2/catch_test_macros.hpp"
#include "irc/parse_caps.hpp"
#include <iterator>

TEST_CASE("simple caps")
{
  const auto output = parse_caps("multi-prefix extended-join account-notify");
  CHECK( output.contains("multi-prefix") );
  CHECK( output.contains("extended-join") );
  CHECK( output.contains("account-notify") );
}

TEST_CASE("key-value")
{
  const auto output = parse_caps("sasl=PLAIN example.com/a=b");
  CHECK( output.contains("sasl") );
  CHECK( output.contains("example.com/a") );

  CHECK( output.at("sasl") == "PLAIN" );
  CHECK( output.at("example.com/a") == "b" );
}

TEST_CASE("nested key-value")
{
  const auto output = parse_caps("draft/multiline=max-bytes=40000,max-lines=10 example.com/a=foo=bar,b=c");
  CHECK( output.contains("draft/multiline") );
  CHECK( output.contains("example.com/a") );

  const auto multiline = output.at("draft/multiline");
  const auto a = output.at("example.com/a");
  CHECK( multiline == "max-bytes=40000,max-lines=10" );
  CHECK ( a == "foo=bar,b=c" );

  const auto multiline_val = parse_cap_keyval(multiline.value());
  const auto a_val = parse_cap_keyval(a.value());
  CHECK( multiline_val.at("max-bytes").has_value() );
  CHECK( multiline_val.at("max-lines").has_value() );
  CHECK( a_val.at("foo").has_value() );
  CHECK( a_val.at("b").has_value() );

  CHECK( multiline_val.at("max-bytes").value() == "40000" );
  CHECK( multiline_val.at("max-lines").value() == "10" );
  CHECK( a_val.at("foo").value() == "bar" );
  CHECK( a_val.at("b").value() == "c" );
}

TEST_CASE("all")
{
  const auto output = parse_caps("message-tags sasl=PLAIN,EXTERNAL draft/multiline=max-bytes=40000,max-lines=10");
  CHECK( output.contains("message-tags") );
  CHECK( output.contains("sasl") );
  CHECK( output.contains("draft/multiline") );

  const auto multiline = output.at("draft/multiline");
  const auto sasl = output.at("sasl");
  const auto message_tags = output.at("message-tags");
  CHECK( !message_tags.has_value() );
  CHECK( sasl == "PLAIN,EXTERNAL" );
  CHECK( multiline == "max-bytes=40000,max-lines=10" );

  const auto multiline_val = parse_cap_keyval(multiline.value());
  const auto sasl_val = parse_cap_val_list(sasl.value());
  CHECK( std::find(sasl_val.begin(), sasl_val.end(), "PLAIN") != sasl_val.end() );
  CHECK( std::find(sasl_val.begin(), sasl_val.end(), "EXTERNAL") != sasl_val.end() );
  CHECK( multiline_val.at("max-bytes").has_value() );
  CHECK( multiline_val.at("max-lines").has_value() );

  CHECK( multiline_val.at("max-bytes").value() == "40000" );
  CHECK( multiline_val.at("max-lines").value() == "10" );
}
