#include "stdafx.h"

#include "xtr/core/PyTextProcessor.h"
#include "xtr/core/PyCore.h"

namespace xtr::core {

using cxxpython::PyCore;

void PyTextProcessor::InitModule(const std::string& key) {
  moduleKey = key;
  isInit = true;
}

std::string PyTextProcessor::Inflect(const std::string& target, const ccl::lang::Morphology& form) const {
  if (!isInit || empty(target)) {
    return target;
  }

  const auto inflect = PyCore::Instance().PyFunction(moduleKey, "inflect");
  if (inflect == nullptr) {
    return target;
  }

  const auto value = inflect("(s, s)", target.c_str(), form.ToString().c_str());
  if (value == nullptr) {
    return target;
  }
  return cxxpython::ToString(value);
}

std::string PyTextProcessor::InflectDependant(const std::string& dependant, const std::string& main) const {
  if (!isInit || empty(dependant) || empty(main)) {
    return dependant;
  }

  const auto inflect_dependant = PyCore::Instance().PyFunction(moduleKey, "inflect_dependant");
  if (inflect_dependant == nullptr) {
    return dependant;
  }

  const auto value = inflect_dependant("(s, s)", dependant.c_str(), main.c_str());
  if (value == nullptr) {
    return dependant;
  }
  return cxxpython::ToString(value);
}

bool PyTextProcessor::IsSubstr(const std::string& needle, const std::string& haystack) const {
  if (TextProcessor::IsSubstr(needle, haystack)) {
    return true;
  } else if (!isInit) {
    return false;
  } else if (const auto find_substr = PyCore::Instance().PyFunction(moduleKey, "find_substr");
             find_substr == nullptr) {
    return false;
  } else if (const auto value = find_substr("(s, s)", needle.c_str(), haystack.c_str());
             value == nullptr) {
    return false;
  } else {
    return cxxpython::ToLong(value.at(0)) != 0 || cxxpython::ToLong(value.at(1)) != 0;
  }
}

} // namespace xtr::core