#include <move_base/convert_data.h>
#include <robot/robot.h>
#include <robot_costmap_2d/cost_values.h>

char* move_base::ConvertData::cost_translation_table_ = NULL;

move_base::ConvertData::ConvertData(robot_costmap_2d::Costmap2DROBOT* costmap, std::string global_frame, bool always_send_full_costmap)
  : costmap_(costmap), global_frame_(global_frame), always_send_full_costmap_(always_send_full_costmap)
{
    if (cost_translation_table_ == NULL)
    {
      cost_translation_table_ = new char[256];
  
      // special values:
      cost_translation_table_[(const int)robot_costmap_2d::PREFERRED_SPACE] = 120;  // Preferred place
      for(int i = (int)robot_costmap_2d::PREFERRED_SPACE+1; i <= (const int)robot_costmap_2d::FREE_SPACE; i++)
        cost_translation_table_[i] = 0;   // NO obstacle
  
      cost_translation_table_[(const int)robot_costmap_2d::CRITICAL_SPACE] = 150;  // CRITICAL_SPACE
      cost_translation_table_[(const int)robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE] = 99;  // INSCRIBED obstacle
      cost_translation_table_[(const int)robot_costmap_2d::LETHAL_OBSTACLE] = 100;  // LETHAL obstacle
      cost_translation_table_[(const int)robot_costmap_2d::NO_INFORMATION] = -1;  // UNKNOWN
  
      // regular cost values scale the range 10 to 252 (inclusive) to fit
      // into 1 to 98 (inclusive).
      for (int i = (int)robot_costmap_2d::FREE_SPACE + 1; i < (const int)robot_costmap_2d::INSCRIBED_INFLATED_OBSTACLE; i++)
      {
        cost_translation_table_[ i ] = char(1 + (97 * (i - 1)) / 251);
      }
    }

    xn_ = yn_ = 0;
    x0_ = costmap_->getCostmap()->getSizeInCellsX();
    y0_ = costmap_->getCostmap()->getSizeInCellsY();
}

move_base::ConvertData::~ConvertData()
{
}

// prepare grid_ message for publication.
void move_base::ConvertData::prepareGrid()
{
  // boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
  double resolution = costmap_->getCostmap()->getResolution();

  grid_.header.frame_id = global_frame_;
  grid_.header.stamp = robot::Time::now();
  grid_.info.resolution = resolution;

  grid_.info.width = costmap_->getCostmap()->getSizeInCellsX();
  grid_.info.height = costmap_->getCostmap()->getSizeInCellsY();

  double wx, wy;
  costmap_->getCostmap()->mapToWorld(0, 0, wx, wy);
  grid_.info.origin.position.x = wx - resolution / 2;
  grid_.info.origin.position.y = wy - resolution / 2;
  grid_.info.origin.position.z = 0.0;
  grid_.info.origin.orientation.w = 1.0;
  saved_origin_x_ = costmap_->getCostmap()->getOriginX();
  saved_origin_y_ = costmap_->getCostmap()->getOriginY();

  grid_.data.resize(grid_.info.width * grid_.info.height);

  unsigned char* data = costmap_->getCostmap()->getCharMap();
  for (unsigned int i = 0; i < grid_.data.size(); i++)
  {
    grid_.data[i] = cost_translation_table_[ data[ i ]];
  }
}

void move_base::ConvertData::updateCostmap(robot_nav_msgs::OccupancyGrid &grid, robot_map_msgs::OccupancyGridUpdate &update, bool &is_updated)
{
  boost::unique_lock<robot_costmap_2d::Costmap2D::mutex_t> lock(*(costmap_->getCostmap()->getMutex()));
  float resolution = costmap_->getCostmap()->getResolution();
  unsigned int x0, y0, xn, yn;
  costmap_->getLayeredCostmap()->getBounds(&x0, &xn, &y0, &yn);
  updateBounds(x0, xn, y0, yn);
  if (always_send_full_costmap_ || grid_.info.resolution != resolution ||
      grid_.info.width != costmap_->getCostmap()->getSizeInCellsX() ||
      grid_.info.height != costmap_->getCostmap()->getSizeInCellsY() ||
      saved_origin_x_ != costmap_->getCostmap()->getOriginX() ||
      saved_origin_y_ != costmap_->getCostmap()->getOriginY())
  {
    prepareGrid();
    grid = grid_;
    is_updated = false;
  }
  else if (x0_ < xn_)
  {
    update.header.stamp = robot::Time::now();
    update.header.frame_id = global_frame_;
    update.x = x0_;
    update.y = y0_;
    update.width = xn_ - x0_;
    update.height = yn_ - y0_;
    update.data.resize(update.width * update.height);

    unsigned int i = 0;
    for (unsigned int y = y0_; y < yn_; y++)
    {
      for (unsigned int x = x0_; x < xn_; x++)
      {
        unsigned char cost = costmap_->getCostmap()->getCost(x, y);
        update.data[i++] = cost_translation_table_[ cost ];
      }
    } 
    is_updated = true;
  }

  xn_ = yn_ = 0;
  x0_ = costmap_->getCostmap()->getSizeInCellsX();
  y0_ = costmap_->getCostmap()->getSizeInCellsY();
}

void move_base::ConvertData::updateFootprint(robot_geometry_msgs::PolygonStamped &footprint)
{
  footprint.header.frame_id = global_frame_;
  footprint.header.stamp = robot::Time::now();
  footprint.polygon = costmap_->getRobotFootprintPolygonStamped().polygon;

}

void move_base::ConvertData::updateBounds(unsigned int x0, unsigned int xn, unsigned int y0, unsigned int yn)
{
  x0_ = std::min(x0, x0_);
  xn_ = std::max(xn, xn_);
  y0_ = std::min(y0, y0_);
  yn_ = std::max(yn, yn_);
}