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

#include <algorithm>

namespace ArgumentParser {

auto ActionMap::Emplace(cm::string_view name, Action action)
  -> std::pair<iterator, bool>
{
  auto const it =
    std::lower_bound(begin(), end(), name,
                     [](value_type const& elem, cm::string_view const& k) {
                       return elem.first < k;
                     });
  return (it != end() && it->first == name)
    ? std::make_pair(it, false)
    : std::make_pair(emplace(it, name, std::move(action)), true);
}

auto ActionMap::Find(cm::string_view name) const -> const_iterator
{
  auto const it =
    std::lower_bound(begin(), end(), name,
                     [](value_type const& elem, cm::string_view const& k) {
                       return elem.first < k;
                     });
  return (it != end() && it->first == name) ? it : end();
}

void Instance::Bind(bool& val)
{
  val = true;
  CurrentString = nullptr;
  CurrentList = nullptr;
  ExpectValue = false;
}

void Instance::Bind(std::string& val)
{
  CurrentString = &val;
  CurrentList = nullptr;
  ExpectValue = true;
}

void Instance::Bind(StringList& val)
{
  CurrentString = nullptr;
  CurrentList = &val;
  ExpectValue = true;
}

void Instance::Bind(MultiStringList& val)
{
  CurrentString = nullptr;
  CurrentList = (static_cast<void>(val.emplace_back()), &val.back());
  ExpectValue = false;
}

void Instance::Consume(cm::string_view arg, void* result,
                       std::vector<std::string>* unparsedArguments,
                       std::vector<std::string>* keywordsMissingValue,
                       std::vector<std::string>* parsedKeywords)
{
  auto const it = Bindings.Find(arg);
  if (it != Bindings.end()) {
    if (parsedKeywords != nullptr) {
      parsedKeywords->emplace_back(arg);
    }
    it->second(*this, result);
    if (ExpectValue && keywordsMissingValue != nullptr) {
      keywordsMissingValue->emplace_back(arg);
    }
    return;
  }

  if (CurrentString != nullptr) {
    CurrentString->assign(std::string(arg));
    CurrentString = nullptr;
    CurrentList = nullptr;
  } else if (CurrentList != nullptr) {
    CurrentList->emplace_back(arg);
  } else if (unparsedArguments != nullptr) {
    unparsedArguments->emplace_back(arg);
  }

  if (ExpectValue) {
    if (keywordsMissingValue != nullptr) {
      keywordsMissingValue->pop_back();
    }
    ExpectValue = false;
  }
}

} // namespace ArgumentParser
