#include <cmath>
#include <iostream>

#include "emc/kinematics/kinematics.h"

int rtapi_app_main(void);
void rtapi_app_exit(void);

namespace {

int near(double actual, double expected)
{
    return std::fabs(actual - expected) < 1e-9;
}

int near_pose(const EmcPose &actual, const EmcPose &expected)
{
    return near(actual.tran.x, expected.tran.x) &&
           near(actual.tran.y, expected.tran.y) &&
           near(actual.tran.z, expected.tran.z) &&
           near(actual.a, expected.a) &&
           near(actual.b, expected.b);
}

void print_pose(const char *prefix, const EmcPose &pose)
{
    std::cout << prefix << "_xyz="
              << pose.tran.x << ","
              << pose.tran.y << ","
              << pose.tran.z << "\n";
    std::cout << prefix << "_ab="
              << pose.a << ","
              << pose.b << "\n";
}

void print_joints(const char *prefix, const double *joints)
{
    std::cout << prefix << "_xyzab="
              << joints[0] << ","
              << joints[1] << ","
              << joints[2] << ","
              << joints[3] << ","
              << joints[4] << "\n";
}

}  // namespace

int main()
{
    const int init_rc = rtapi_app_main();
    std::cout << "scorbot_init=" << init_rc << "\n";
    std::cout << "scorbot_type=" << kinematicsType() << "\n";
    std::cout << "scorbot_switchable=" << kinematicsSwitchable() << "\n";

    double joints[9]{};
    joints[0] = 25.0;
    joints[1] = 20.0;
    joints[2] = 10.0;
    joints[3] = 4.0;
    joints[4] = 5.0;

    KINEMATICS_FORWARD_FLAGS fflags = 0;
    KINEMATICS_INVERSE_FLAGS iflags = 0;
    EmcPose forward_pose{};
    const int forward_rc = kinematicsForward(joints, &forward_pose, &fflags, &iflags);
    std::cout << "scorbot_forward=" << forward_rc << "\n";
    print_pose("scorbot_forward", forward_pose);

    double inverse_joints[9]{};
    const int inverse_rc = kinematicsInverse(&forward_pose, inverse_joints, &iflags, &fflags);
    std::cout << "scorbot_inverse=" << inverse_rc << "\n";
    print_joints("scorbot_inverse", inverse_joints);

    EmcPose roundtrip_pose{};
    const int roundtrip_rc = kinematicsForward(inverse_joints, &roundtrip_pose, &fflags, &iflags);
    std::cout << "scorbot_roundtrip_forward=" << roundtrip_rc << "\n";
    print_pose("scorbot_roundtrip", roundtrip_pose);
    std::cout << "scorbot_roundtrip_pose=" << near_pose(roundtrip_pose, forward_pose) << "\n";

    rtapi_app_exit();
    return 0;
}
