from django.http import JsonResponse, HttpResponse
from django.middleware.csrf import get_token
from django.shortcuts import render, redirect
from django.dispatch import receiver

from mqtt.mqtt import client as mqtt_client
from mqtt.signals import mqtt_message_received

MESSAGE = b""

def publish_message(request):
    # request_data = json.loads(request.body)
    topic = request.POST['topic']
    msg = request.POST['msg']
    rc, mid = mqtt_client.publish(topic, msg)
    return JsonResponse({'code': rc})


def index(request):
    global MESSAGE
    token = get_token(request)
    return render(request, 'index.html', {'token': token, 'msg': MESSAGE.decode('utf-8')})


@receiver(mqtt_message_received) 
def show_message(sender, **kwargs):
    global MESSAGE
    print('Received message:', kwargs['message'])
    MESSAGE = kwargs['message']
