#! /usr/bin/env python

from __future__ import print_function
import rospy
import sys
from webmysqlauth.webmysql import WebMysql
from rosauth.srv import Authentication,AuthenticationResponse

db = None
tablename = ''
def authenticate(req):

    rospy.loginfo("Request [mac:%s , client:%s , dest:%s, rand:%s, t:%s, level:%s, end:%s]"%(req.mac, req.client, req.dest, req.rand, req.t, req.level , req.end  ))
    authenticated = False
    if db is None:
        rospy.loginfo("authenticated result=%s"%( authenticated ))
        return AuthenticationResponse(authenticated)

    try:
        result = db.select(tablename, "name = '" + req.client +"' " ,'id','name')
        rospy.loginfo(result)
        if result is not None:
            authenticated = True

    except Exception, e:
        rospy.logerr("Error:%s"%( str(e) ))
    
    rospy.loginfo("authenticated result=%s"%( authenticated ))
    return AuthenticationResponse(authenticated)
 



if __name__ == '__main__':
    rospy.init_node("ros_webmysqlauth")

    ##################################################
    # Parameter handling                             #
    ##################################################
    hostname = rospy.get_param('~hostname', 'localhost')
    username = rospy.get_param('~username', '')
    password = rospy.get_param('~password', '')
    database = rospy.get_param('~database', '')
    tablename = rospy.get_param('~tablename', 'users')

    db =  WebMysql(host=hostname, user=username, password=password, database=database)
    rospy.loginfo("hostname=%s"%( hostname ))
    rospy.loginfo("username=%s"%( username ))
    rospy.loginfo("password=%s"%( password ))
    rospy.loginfo("database=%s"%( database ))
    rospy.loginfo("tablename=%s"%( tablename ))

    s = rospy.Service('authenticate',Authentication, authenticate)
    rospy.loginfo("ROS Web mysql Authentication Server Started")
    rospy.spin()
