import logging
import json
import donwlink_message
import asyncio
from azure.eventhub import EventHubConsumerClient

connection_str = "Endpoint=sb://ihsuprodamres091dednamespace.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=v0auIwbmqfBDz3BY8aZtbnOzg8+6119LWylk1Jq1G0A=;EntityPath=iothub-ehub-agrihub-3199035-0595c5c32a"
consumer_group = '$Default'
eventhub_name = 'iothub-ehub-agrihub-3199035-0595c5c32a'
client = EventHubConsumerClient.from_connection_string(connection_str, consumer_group, eventhub_name=eventhub_name)
logger = logging.getLogger("azure.eventhub")
logging.basicConfig(level=logging.INFO)

def background(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)
    return wrapped

def on_event(partition_context, event):
    #logger.info("Received event from partition {}".format(partition_context.partition_id))
    #print("PartitionContext:  ", partition_context)
    partition_context.update_checkpoint(event)
    #print(event)
    print("JSON: -->",event.body_as_json(encoding='UTF-8'))
    message_arrrived = event.body_as_json(encoding='UTF-8')
    if message_arrrived["st"] > 5:
        request_sample()

@background
def request_sample():
    donwlink_message.send_to_device("RequestAudioSample")

def start_event_hub_listener():
    client.receive( on_event=on_event, partition_id="0")