/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2017, Locus Robotics
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef METRATRONIK_TECHNIK_H_INCLUDE_
#define METRATRONIK_TECHNIK_H_INCLUDE_

#include <dwb_local_planner/trajectory_critic.h>
#include <geometry_msgs/PoseStamped.h>
#include <string>
#include <vector>
#include <iostream>

namespace dwb_critics
{
  /* data */
  struct lineEquation
  {
    geometry_msgs::Pose2D Gi; /* 𝑮𝒊(𝒙𝒊,𝒚𝒊)  */
    geometry_msgs::Pose2D Gj; /* 𝑮𝒋(𝒙𝒋,𝒚𝒋)  */
    float a, b, c;                 /* 𝒂𝒙+𝒃𝒚+𝒄=𝟎 */
  };

  /* Save data present position */
  struct presentPosition
  {
    float Gxh, Gyh;         /* 𝑮𝒋(𝒙h,𝒚h) The head position in Robot */
    float Yaw_degree;       /* Angle of Robot (degree)              */
    float Yaw_rad;          /* Angle of Robot (degree)              */
    float error_line;       /* 𝒆(𝑮,𝒍𝒊𝒏𝒆)=|𝒂𝒙+𝒃𝒚+𝒄|/sqrt(𝒂^2+𝒃^2)    */
    double distanceToEnd;   /* The distance from robot to End point  */
    double distanceToStart; /* The distance from robot to End point  */
  };

  class NoSolution : public std::exception
  {
  public:
    const char *what() const throw()
    {
      return "Robot cannot calculate error line!";
    }
  };

  class MetratronikTechnikCritic : public dwb_local_planner::TrajectoryCritic
  {
  public:
    void onInit() override;
    void reset() override;
    bool prepare(const geometry_msgs::Pose2D &pose, const nav_2d_msgs::Twist2D &vel,
                 const geometry_msgs::Pose2D &goal, const nav_2d_msgs::Path2D &global_plan) override;
    double scoreTrajectory(const dwb_msgs::Trajectory2D &traj) override;

  protected:
    /**
     * @brief Assuming that this is an actual rotation when near the goal, score the trajectory.
     *
     * Phương pháp này (dễ dàng ghi đè) giả định rằng người phê bình đang ở giai đoạn thứ ba (như mô tả ở trên)
     * và trả về một số điểm cho quỹ đạo tương ứng với độ lệch mục tiêu.
     * @param traj Trajectory to score
     * @return numeric score
     */
    virtual double scoreMetratronikTechnik(const dwb_msgs::Trajectory2D &traj);
    bool getPosition(const geometry_msgs::Pose2D &robot_pose, const nav_2d_msgs::Path2D &global_plan, double &position);
    unsigned getGoalIndex(const geometry_msgs::Pose2D &robot_pose,
                          const std::vector<geometry_msgs::Pose2D> &plan,
                          unsigned int start_index,
                          unsigned int last_valid_index) const;

    /**
     * @brief To caculated the equation of the line
     * @param start_point   start point of the line
     * @param end_point     end point of the line
     */
    bool getLine(geometry_msgs::Pose2D start_point, geometry_msgs::Pose2D end_point, lineEquation &leq);

    /**
     * @brief Calculating error
     * @param[in] Lm            The distance from the center of the wheel axis to the center line
     * @param[in] Yaw_degree    Angle of Robot (degree)
     */
    presentPosition calculateError(const lineEquation &leq, const float Lm, const geometry_msgs::Pose2D robot_pose, float pha);

    bool in_window_, running_;
    double sq_window_;
    double xy_local_goal_tolerance_;
    double xy_local_goal_tolerance_sq_; ///< Cached squared tolerance
    double current_speed_, stopped_velocity_;
    double slowing_factor_;
    double current_position_;
    double angle_threshold_;
    double Lm_;
    double dxy_sq_;
    std::vector<geometry_msgs::Pose2D> reached_intermediate_goals_;
  };
}
#endif