#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) &&
           near(actual.c, expected.c) &&
           near(actual.u, expected.u) &&
           near(actual.v, expected.v) &&
           near(actual.w, expected.w);
}

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 << "_abcuvw="
              << pose.a << ","
              << pose.b << ","
              << pose.c << ","
              << pose.u << ","
              << pose.v << ","
              << pose.w << "\n";
}

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

}  // namespace

int main()
{
    const int init_rc = rtapi_app_main();
    std::cout << "lineardelta_init=" << init_rc << "\n";
    std::cout << "lineardelta_type=" << kinematicsType() << "\n";
    std::cout << "lineardelta_switchable=" << kinematicsSwitchable() << "\n";

    EmcPose pose{};
    pose.tran.x = 10.0;
    pose.tran.y = 20.0;
    pose.tran.z = -30.0;
    pose.a = 1.0;
    pose.b = 2.0;
    pose.c = 3.0;
    pose.u = 4.0;
    pose.v = 5.0;
    pose.w = 6.0;

    KINEMATICS_FORWARD_FLAGS fflags = 0;
    KINEMATICS_INVERSE_FLAGS iflags = 0;
    double inverse_joints[9]{};
    const int inverse_rc = kinematicsInverse(&pose, inverse_joints, &iflags, &fflags);
    std::cout << "lineardelta_inverse=" << inverse_rc << "\n";
    print_joints("lineardelta_inverse", inverse_joints);

    EmcPose forward_pose{};
    const int forward_rc = kinematicsForward(inverse_joints, &forward_pose, &fflags, &iflags);
    std::cout << "lineardelta_forward=" << forward_rc << "\n";
    print_pose("lineardelta_forward", forward_pose);
    std::cout << "lineardelta_roundtrip_pose=" << near_pose(forward_pose, pose) << "\n";

    rtapi_app_exit();
    return 0;
}
