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

#include <cstddef>
#include <deque>
#include <map>
#include <utility>

#include <cmext/algorithm>

#include "cmMakefile.h"
#include "cmProperty.h"
#include "cmRange.h"
#include "cmSearchPath.h"
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"

class cmExecutionStatus;

cmFindBase::cmFindBase(cmExecutionStatus& status)
  : cmFindCommon(status)
{
}

bool cmFindBase::ParseArguments(std::vector<std::string> const& argsIn)
{
  if (argsIn.size() < 2) {
    SetError("called with incorrect number of arguments");
    return false;
  }

  // copy argsIn into args so it can be modified,
  // in the process extract the DOC "documentation"
  size_t size = argsIn.size();
  std::vector<std::string> args;
  bool foundDoc = false;
  for (unsigned int j = 0; j < size; ++j) {
    if (foundDoc || argsIn[j] != "DOC") {
      if (argsIn[j] == "ENV") {
        if (j + 1 < size) {
          j++;
          cmSystemTools::GetPath(args, argsIn[j].c_str());
        }
      } else {
        args.push_back(argsIn[j]);
      }
    } else {
      if (j + 1 < size) {
        foundDoc = true;
        VariableDocumentation = argsIn[j + 1];
        j++;
        if (j >= size) {
          break;
        }
      }
    }
  }
  if (args.size() < 2) {
    SetError("called with incorrect number of arguments");
    return false;
  }
  VariableName = args[0];
  if (CheckForVariableInCache()) {
    AlreadyInCache = true;
    return true;
  }
  AlreadyInCache = false;

  // Find what search path locations have been enabled/disable
  SelectDefaultSearchModes();

  // Find the current root path mode.
  SelectDefaultRootPathMode();

  // Find the current bundle/framework search policy.
  SelectDefaultMacMode();

  bool newStyle = false;
  enum Doing
  {
    DoingNone,
    DoingNames,
    DoingPaths,
    DoingPathSuffixes,
    DoingHints
  };
  Doing doing = DoingNames; // assume it starts with a name
  for (unsigned int j = 1; j < args.size(); ++j) {
    if (args[j] == "NAMES") {
      doing = DoingNames;
      newStyle = true;
    } else if (args[j] == "PATHS") {
      doing = DoingPaths;
      newStyle = true;
    } else if (args[j] == "HINTS") {
      doing = DoingHints;
      newStyle = true;
    } else if (args[j] == "PATH_SUFFIXES") {
      doing = DoingPathSuffixes;
      newStyle = true;
    } else if (args[j] == "NAMES_PER_DIR") {
      doing = DoingNone;
      if (NamesPerDirAllowed) {
        NamesPerDir = true;
      } else {
        SetError("does not support NAMES_PER_DIR");
        return false;
      }
    } else if (args[j] == "NO_SYSTEM_PATH") {
      doing = DoingNone;
      NoDefaultPath = true;
    } else if (args[j] == "REQUIRED") {
      doing = DoingNone;
      Required = true;
      newStyle = true;
    } else if (CheckCommonArgument(args[j])) {
      doing = DoingNone;
    } else {
      // Some common arguments were accidentally supported by CMake
      // 2.4 and 2.6.0 in the short-hand form of the command, so we
      // must support it even though it is not documented.
      if (doing == DoingNames) {
        Names.push_back(args[j]);
      } else if (doing == DoingPaths) {
        UserGuessArgs.push_back(args[j]);
      } else if (doing == DoingHints) {
        UserHintsArgs.push_back(args[j]);
      } else if (doing == DoingPathSuffixes) {
        AddPathSuffix(args[j]);
      }
    }
  }

  if (VariableDocumentation.empty()) {
    VariableDocumentation = "Where can ";
    if (Names.empty()) {
      VariableDocumentation += "the (unknown) library be found";
    } else if (Names.size() == 1) {
      VariableDocumentation += "the " + Names.front() + " library be found";
    } else {
      VariableDocumentation += "one of the ";
      VariableDocumentation += cmJoin(cmMakeRange(Names).retreat(1), ", ");
      VariableDocumentation += " or " + Names.back() + " libraries be found";
    }
  }

  // look for old style
  // FIND_*(VAR name path1 path2 ...)
  if (!newStyle && !Names.empty()) {
    // All the short-hand arguments have been recorded as names.
    std::vector<std::string> shortArgs = Names;
    Names.clear(); // clear out any values in Names
    Names.push_back(shortArgs[0]);
    cm::append(UserGuessArgs, shortArgs.begin() + 1, shortArgs.end());
  }
  ExpandPaths();

  ComputeFinalPaths();

  return true;
}

void cmFindBase::ExpandPaths()
{
  if (!NoDefaultPath) {
    if (!NoPackageRootPath) {
      FillPackageRootPath();
    }
    if (!NoCMakePath) {
      FillCMakeVariablePath();
    }
    if (!NoCMakeEnvironmentPath) {
      FillCMakeEnvironmentPath();
    }
  }
  FillUserHintsPath();
  if (!NoDefaultPath) {
    if (!NoSystemEnvironmentPath) {
      FillSystemEnvironmentPath();
    }
    if (!NoCMakeSystemPath) {
      FillCMakeSystemVariablePath();
    }
  }
  FillUserGuessPath();
}

void cmFindBase::FillCMakeEnvironmentPath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::CMakeEnvironment];

  // Add CMAKE_*_PATH environment variables
  std::string var = cmStrCat("CMAKE_", CMakePathName, "_PATH");
  paths.AddEnvPrefixPath("CMAKE_PREFIX_PATH");
  paths.AddEnvPath(var);

  if (CMakePathName == "PROGRAM") {
    paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  } else {
    paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  }
  paths.AddSuffixes(SearchPathSuffixes);
}

void cmFindBase::FillPackageRootPath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::PackageRoot];

  // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  for (std::vector<std::string> const& pkgPaths :
       cmReverseRange(Makefile->FindPackageRootPathStack)) {
    paths.AddPrefixPaths(pkgPaths);
  }

  paths.AddSuffixes(SearchPathSuffixes);
}

void cmFindBase::FillCMakeVariablePath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::CMake];

  // Add CMake variables of the same name as the previous environment
  // variables CMAKE_*_PATH to be used most of the time with -D
  // command line options
  std::string var = cmStrCat("CMAKE_", CMakePathName, "_PATH");
  paths.AddCMakePrefixPath("CMAKE_PREFIX_PATH");
  paths.AddCMakePath(var);

  if (CMakePathName == "PROGRAM") {
    paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  } else {
    paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  }
  paths.AddSuffixes(SearchPathSuffixes);
}

void cmFindBase::FillSystemEnvironmentPath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::SystemEnvironment];

  // Add LIB or INCLUDE
  if (!EnvironmentPath.empty()) {
    paths.AddEnvPath(EnvironmentPath);
#if defined(_WIN32) || defined(__CYGWIN__)
    paths.AddEnvPrefixPath("PATH", true);
#endif
  }
  // Add PATH
  paths.AddEnvPath("PATH");
  paths.AddSuffixes(SearchPathSuffixes);
}

void cmFindBase::FillCMakeSystemVariablePath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::CMakeSystem];

  std::string var = cmStrCat("CMAKE_SYSTEM_", CMakePathName, "_PATH");
  paths.AddCMakePrefixPath("CMAKE_SYSTEM_PREFIX_PATH");
  paths.AddCMakePath(var);

  if (CMakePathName == "PROGRAM") {
    paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  } else {
    paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  }
  paths.AddSuffixes(SearchPathSuffixes);
}

void cmFindBase::FillUserHintsPath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::Hints];

  for (std::string const& p : UserHintsArgs) {
    paths.AddUserPath(p);
  }
  paths.AddSuffixes(SearchPathSuffixes);
}

void cmFindBase::FillUserGuessPath()
{
  cmSearchPath& paths = LabeledPaths[PathLabel::Guess];

  for (std::string const& p : UserGuessArgs) {
    paths.AddUserPath(p);
  }
  paths.AddSuffixes(SearchPathSuffixes);
}

bool cmFindBase::CheckForVariableInCache()
{
  if (cmProp cacheValue = Makefile->GetDefinition(VariableName)) {
    cmState* state = Makefile->GetState();
    cmProp cacheEntry = state->GetCacheEntryValue(VariableName);
    bool found = !cmIsNOTFOUND(*cacheValue);
    bool cached = cacheEntry != nullptr;
    if (found) {
      // If the user specifies the entry on the command line without a
      // type we should add the type and docstring but keep the
      // original value.  Tell the subclass implementations to do
      // this.
      if (cached &&
          state->GetCacheEntryType(VariableName) ==
            cmStateEnums::UNINITIALIZED) {
        AlreadyInCacheWithoutMetaInfo = true;
      }
      return true;
    }
    if (cached) {
      cmProp hs = state->GetCacheEntryProperty(VariableName, "HELPSTRING");
      VariableDocumentation = hs ? *hs : "(none)";
    }
  }
  return false;
}

cmFindBaseDebugState::cmFindBaseDebugState(std::string commandName,
                                           cmFindBase const* findBase)
  : FindCommand(findBase)
  , CommandName(std::move(commandName))
{
}

cmFindBaseDebugState::~cmFindBaseDebugState()
{
  if (FindCommand->DebugMode) {
    std::string buffer =
      cmStrCat(CommandName, " called with the following settings:\n");
    buffer += cmStrCat("  VAR: ", FindCommand->VariableName, "\n");
    buffer += cmStrCat(
      "  NAMES: ", cmWrap("\"", FindCommand->Names, "\"", "\n         "),
      "\n");
    buffer +=
      cmStrCat("  Documentation: ", FindCommand->VariableDocumentation, "\n");
    buffer += "  Framework\n";
    buffer += cmStrCat(
      "    Only Search Frameworks: ", FindCommand->SearchFrameworkOnly, "\n");

    buffer += cmStrCat(
      "    Search Frameworks Last: ", FindCommand->SearchFrameworkLast, "\n");
    buffer += cmStrCat("    Search Frameworks First: ",
                       FindCommand->SearchFrameworkFirst, "\n");
    buffer += "  AppBundle\n";
    buffer += cmStrCat(
      "    Only Search AppBundle: ", FindCommand->SearchAppBundleOnly, "\n");
    buffer += cmStrCat(
      "    Search AppBundle Last: ", FindCommand->SearchAppBundleLast, "\n");
    buffer += cmStrCat(
      "    Search AppBundle First: ", FindCommand->SearchAppBundleFirst, "\n");

    if (FindCommand->NoDefaultPath) {
      buffer += "  NO_DEFAULT_PATH Enabled\n";
    } else {
      buffer +=
        cmStrCat("  CMAKE_FIND_USE_CMAKE_PATH: ", !FindCommand->NoCMakePath,
                 "\n", "  CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH: ",
                 !FindCommand->NoCMakeEnvironmentPath, "\n",
                 "  CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH: ",
                 !FindCommand->NoSystemEnvironmentPath, "\n",
                 "  CMAKE_FIND_USE_CMAKE_SYSTEM_PATH: ",
                 !FindCommand->NoCMakeSystemPath, "\n");
    }

    buffer += cmStrCat(CommandName, " considered the following locations:\n");
    for (auto const& state : FailedSearchLocations) {
      std::string path = cmStrCat("  ", state.path);
      if (!state.regexName.empty()) {
        path = cmStrCat(path, "/", state.regexName);
      }
      buffer += cmStrCat(path, "\n");
    }

    if (!FoundSearchLocation.path.empty()) {
      buffer +=
        cmStrCat("The item was found at\n  ", FoundSearchLocation.path, "\n");
    } else {
      buffer += "The item was not found.\n";
    }

    FindCommand->DebugMessage(buffer);
  }
}

void cmFindBaseDebugState::FoundAt(std::string const& path,
                                   std::string regexName)
{
  if (FindCommand->DebugMode) {
    FoundSearchLocation = DebugLibState{ std::move(regexName), path };
  }
}

void cmFindBaseDebugState::FailedAt(std::string const& path,
                                    std::string regexName)
{
  if (FindCommand->DebugMode) {
    FailedSearchLocations.emplace_back(std::move(regexName), path);
  }
}
