/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */

#include "cmCxxModuleDepfileParser.h"

#include "cm_jsoncpp_reader.h"
#include "cm_jsoncpp_value.h"
#include "cmsys/FStream.hxx"
#include <map>

#include "cmAlgorithms.h"
#include "cmSystemTools.h"

bool cmCxxModuleDepfileParser::ParseGNU(std::string const& arg_pp, cmSourceInfo* info)
{
  Json::Value ppio;
  Json::Value const& ppi = ppio;
  cmsys::ifstream ppf(arg_pp.c_str(), std::ios::in | std::ios::binary);
  {
    Json::Reader reader;
    if (!reader.parse(ppf, ppio, false)) {
      cmSystemTools::Error("-E cmake_ninja_depends failed to parse ",
                            arg_pp.c_str(),
                            reader.getFormattedErrorMessages().c_str());
      return false;
    }
  }

  Json::Value const& provides = ppi["provides"];
  if (provides.isArray()) {
    for (auto const& provide : provides) {
      info->Provides.insert(provide.asString());
    }
  }

  Json::Value const& logical_provides = ppi["logical-provides"];
  if (logical_provides.isObject()) {
    for (auto i = logical_provides.begin(); i != logical_provides.end(); ++i) {
      info->LogicalProvides[i.key().asString()] = i->asString();
    }
  }

  Json::Value const& requires = ppi["requires"];
  if (requires.isArray()) {
    for (auto const& require : requires) {
      info->Requires.insert(require.asString());
    }
  }

  Json::Value const& depends = ppi["depends"];
  if (depends.isArray()) {
    for (auto const& depend : depends) {
      info->Includes.insert(depend.asString());
    }
  }

  return true;
}
