import sys
import rospy

from fiducial_transform.msg import id_pos_angle
from fiducial_msgs.msg import FiducialTransformArray
from tf.transformations import euler_from_quaternion

transform_topic = rospy.get_param("transform_topic", '/fiducial_transforms')
output = rospy.get_param("output", 'True')

pub = rospy.Publisher('marker_id_pos_angle', id_pos_angle, queue_size=10)
'''
This callback function listens to fiducial messages that describe the translation and rotation of markers w.r.t. to the camera and transforms them to a position in the 2d plane and the angle of the robot in the plane
'''
def callback(data):
    for d in data.transforms:
        id = d.fiducial_id

        q = d.transform.rotation
        t = d.transform.translation

        euler = euler_from_quaternion([q.x, q.y, q.z, q.w])

        m = id_pos_angle()
        m.id = id
        m.x = t.x
        m.y = -t.y
        m.angle = -euler[2]

        if output == 'True':
            print("(marker_id, pos_x, pos_y, angle) = ({}, {}, {}, {})".format(m.id, m.x, m.y, m.angle))

        pub.publish(m)

def main(args):
    rospy.init_node('fiducial_transform_node', anonymous=True)

    print("Starting subscriber listening for {} topic".format(transform_topic))
    quaternion_sub = rospy.Subscriber(transform_topic, FiducialTransformArray, callback)

    rospy.spin()

if __name__ == '__main__':
    main(sys.argv)
