#include <mkt_plugins/xy_theta_iterator.h>
#include <robot_nav_2d_utils/parameters.h>
#include <memory>

namespace mkt_plugins
{
XYThetaIterator::XYThetaIterator()
  : vx_samples_(0),
    vy_samples_(0),
    vtheta_samples_(0),
    kinematics_(nullptr),
    x_it_(nullptr),
    y_it_(nullptr),
    th_it_(nullptr)
{
}

XYThetaIterator::~XYThetaIterator()
{
}

void XYThetaIterator::initialize(const robot::NodeHandle& nh, KinematicParameters::Ptr kinematics) 
{
  kinematics_ = kinematics;
  nh.param("vx_samples", vx_samples_, 20);
  nh.param("vy_samples", vy_samples_, 5);
  vtheta_samples_ = robot_nav_2d_utils::loadParameterWithDeprecation(nh, "vtheta_samples", "vth_samples", 20);
}

void XYThetaIterator::startNewIteration(const robot_nav_2d_msgs::Twist2D& current_velocity, double dt)
{
  x_it_ = std::make_shared<OneDVelocityIterator>("x_it_", current_velocity.x, kinematics_->getDirect()[0], kinematics_->getMinX(), kinematics_->getMaxX(),
                                                 kinematics_->getAccX(), kinematics_->getDecelX(), dt, vx_samples_);
  
  y_it_ = std::make_shared<OneDVelocityIterator>("y_it_", current_velocity.y, kinematics_->getDirect()[1], kinematics_->getMinY(), kinematics_->getMaxY(),
                                                 kinematics_->getAccY(), kinematics_->getDecelY(), dt, vy_samples_);
  
  th_it_ = std::make_shared<OneDVelocityIterator>("th_it_", current_velocity.theta, kinematics_->getDirect()[2], kinematics_->getMinTheta(), kinematics_->getMaxTheta(),
                                                  kinematics_->getAccTheta(), kinematics_->getDecelTheta(), dt, vtheta_samples_);
}

bool XYThetaIterator::hasMoreTwists()
{
  return x_it_ && !x_it_->isFinished();
}

robot_nav_2d_msgs::Twist2D XYThetaIterator::nextTwist()
{
  robot_nav_2d_msgs::Twist2D velocity;
  velocity.x = x_it_->getVelocity();
  velocity.y = y_it_->getVelocity();
  velocity.theta = th_it_->getVelocity();
  iterateToValidVelocity();
  return velocity;
}

robot_nav_2d_msgs::Twist2D XYThetaIterator::getTwist()
{
  robot_nav_2d_msgs::Twist2D velocity;
  velocity.x = x_it_->getVelocity();
  velocity.y = y_it_->getVelocity();
  velocity.theta = th_it_->getVelocity();
  return velocity;
}

bool XYThetaIterator::isValidVelocity()
{
  return kinematics_->isValidSpeed(x_it_->getVelocity(), y_it_->getVelocity(), th_it_->getVelocity());
}

void XYThetaIterator::iterateToValidVelocity()
{
  bool valid = false;
  while (!valid && hasMoreTwists())
  {
    ++(*th_it_);
    if (th_it_->isFinished())
    {
      th_it_->reset();
      ++(*y_it_);
      if (y_it_->isFinished())
      {
        y_it_->reset();
        ++(*x_it_);
      }
    }
    valid = isValidVelocity();
  }
}

} // namespace mkt_plugins

