# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ==============================================================================

import coreasync

HOST = '10.3.3.221'
PORT = 5000

@coreasync.concurrent
def handle_client(address, message):
    print 'Message "%s" Received from %s' % (message, address)
    yield

def send_ping(socket):
    yield socket.sendBroadcast(PORT, 'PING')

@coreasync.concurrent
def serverLoop(socket):
    while True:
        message, address = yield socket.recvFrom()
        yield handle_client(address, message)

if __name__ == '__main__':
    socket = coreasync.Socket.udpBroadcast('', PORT)

    serverLoop(socket)
    coreasync.dispatch_timed(lambda s=socket: send_ping(s), 2.0)

    coreasync.runloop()

    import time
    print 'TIMEOUT', time.time()

def concurrent_func(text):
    for i in range(5):
        print text
        yield

if __name__ == '__main__':
    if 1:
        main_queue = coreasync.dispatch_get_main_queue()
        queue2 = coreasync.dispatch_queue_create('queue2')
        queue3 = coreasync.dispatch_queue_create('queue3')

        coreasync.dispatch_async(main_queue, foo())
        coreasync.dispatch_timed(timed_func, 2.0, 7)

        data = ['Test 1', 'Test 2', 'Test 3']
        coreasync.dispatch_apply(len(data), queue2, lambda n: work(n, data[n]))

        coreasync.dispatch_repeat(10, queue3, repeat_func)
    else:
        coreasync.dispatch_concurrent(lambda: concurrent_func("Concurrent 1"))
        coreasync.dispatch_concurrent(lambda: concurrent_func("Concurrent 2"))
        coreasync.dispatch_concurrent(lambda: concurrent_func("Concurrent 3"))
        coreasync.dispatch_concurrent(lambda: concurrent_func("Concurrent 4"))
        coreasync.dispatch_concurrent(lambda: concurrent_func("Concurrent 5"))


    coreasync.runloop()