# from http://william-os4y.livejournal.com/
# http://www.opensource4you.com/cgi-bin/gitweb.cgi
import ctypes
import sys

libevent=ctypes.cdll.LoadLibrary('libevent.so.1')
i = 0
def root_handler(req, *arg):
    global i
    i += 1
    #print "got request:", req, arg
    libevent.evbuffer_new.restype=ctypes.c_void_p
    #Build a buffer and put page content into it
    buf=libevent.evbuffer_new()
    libevent.evbuffer_add_printf.argtypes=[ctypes.c_void_p, ctypes.c_char_p]
    
    libevent.evbuffer_add_printf(buf,"Hello world"+str(i)+"!\n\n")
    #send the buffer with a return code of 200
    libevent.evhttp_send_reply.argtypes=[ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p]
    libevent.evhttp_send_reply(req, 200, "OK", buf)
    return 1


    
def main():
    #We just initialise and give the server address and port
    libevent.event_init()
    libevent.evhttp_start.argtypes=[ctypes.c_char_p, ctypes.c_short]
    libevent.evhttp_start.restype=ctypes.c_void_p
    http=libevent.evhttp_start('0.0.0.0',8090)
    #we lik the call to root_handler at a request of "/"
    FUNC=ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p)
    libevent.evhttp_set_cb.argtypes=[ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]
    libevent.evhttp_set_cb(http,"/",FUNC(root_handler), None)
    #we loop and wait events ;-)
    libevent.event_dispatch()
    #we close the loop
    print "end loop main" 
    libevent.evhttp_free.argtypes=[ctypes.c_void_p]
    libevent.evhttp_free(http)

if __name__=="__main__":
    main()

