#!/usr/bin/env python

#Created by Jonas Tjahjadi on 11/26/2017 as part of the ROS Programming Assignment
#"a natural language processor"

#imports
import rospy
#regex
import re
#import code generated by catkin
from ros_programming_assignment.srv import FakeNLP, FakeNLPResponse

class FakeNLPService():
	#CONSTRUCTOR METHOD
	def __init__(self, name):
		#register service behavior with the service name, service, and callback method parameters
		self.service = rospy.Service(name, FakeNLP, self.process_string)

	#SERVICE CALLBACK METHOD
	def process_string(self, request):
		#determine if command entered is valid, return 0 if not (so don't execute any action)
		requestString = str(request)
		floatList = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", requestString)
		#regex sees something wrong
		if len(floatList) > 1 or len(floatList) == 0:
			print "Command '" + requestString + "' is not valid, service returning 0."
			return FakeNLPResponse(0)
		#OK, return the float element that is the first element of list
		else:
			return FakeNLPResponse(float(floatList[0]))

#initialize node, create instance of NLP server and spin to give control to ROS in context switching
if __name__ == '__main__':
	rospy.init_node('FakeNLP_server')
	FakeNLPService('fake_nlp')
	rospy.spin()

