#! /usr/bin/env python
PKG='sr_move_arm'
import roslib; roslib.load_manifest(PKG)
import rospy
import unittest

import actionlib
from object_manipulation_msgs.msg import *
from sensor_msgs.msg import *
import math

class HandPostureExecutionTest(unittest.TestCase):

    def assertJointPos(self, joint_name, ok_pos):
        """Test a joints position. Pos is in degrees."""
        msg = rospy.wait_for_message('/gazebo/joint_states', JointState, timeout = 3.0)
        pos = round(math.degrees(msg.position[msg.name.index(joint_name)]), 0)
        self.assertEqual( pos, ok_pos,
                "Joint %s is not at position %i degrees, got %i"%(joint_name, ok_pos, pos) )

    def test_basic(self):
        client = actionlib.SimpleActionClient(
                '/right_arm/hand_posture_execution',GraspHandPostureExecutionAction)
        client.wait_for_server()

        jnames = ['FFJ4', 'FFJ3', 'FFJ0',
                'MFJ4', 'MFJ3', 'MFJ0',
                'RFJ4', 'RFJ3', 'RFJ0',
                'LFJ5', 'LFJ4', 'LFJ3', 'LFJ0',
                'THJ5', 'THJ4', 'THJ3', 'THJ2', 'THJ1']

        # We send a pre grasp followed by a grasp to test the 2 flows through
        # the action server.
        # TODO: Add a release at the end

        # Zero the hand
        goal = GraspHandPostureExecutionGoal()
        goal.goal = GraspHandPostureExecutionGoal.PRE_GRASP
        goal.grasp.pre_grasp_posture = JointState()
        goal.grasp.pre_grasp_posture.name = jnames
        goal.grasp.pre_grasp_posture.position = [0] * len(jnames)
        client.send_goal(goal)
        client.wait_for_result(rospy.Duration.from_sec(5.0))
        # Wait for the move. TODO: Check the action state instead of sleeping
        rospy.sleep(10.0)
        self.assertJointPos("THJ4", 0)

        # Move the thumb in
        target_pos = 70 # deg
        goal = GraspHandPostureExecutionGoal()
        goal.goal = GraspHandPostureExecutionGoal.GRASP
        goal.grasp.grasp_posture = JointState()
        goal.grasp.grasp_posture.name = jnames
        goal.grasp.grasp_posture.position = [0] * len(jnames)
        goal.grasp.grasp_posture.position[jnames.index("THJ4")] = math.radians(target_pos)
        client.send_goal(goal)
        client.wait_for_result(rospy.Duration.from_sec(5.0))
        # Wait for the move. TODO: Check the action state instead of sleeping
        rospy.sleep(20.0)
        self.assertJointPos("THJ4", target_pos)



if __name__ == '__main__':
    rospy.sleep(15.0) # Dirty little sleep to wait for things to settle
    import rostest
    rospy.init_node('hand_posture_execution_test')
    rostest.rosrun(PKG, 'hand_posture_execution_test', HandPostureExecutionTest)

