import os
import sys
import django
import paho.mqtt.client as mqtt
import logging
import json
from django.conf import settings

CUR_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(CUR_DIR)
sys.path.insert(0, BASE_DIR)

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
django.setup()

from apps.enm.services import insert_mplogx_from_king_mqtt

_logger = logging.getLogger("log")


def on_connect(mqttc, userdata, flags, rc, properties):
    if rc == 0:
        if settings.KING_ENABLED:  # 订阅亚控的mqtt转发
            mqttc.subscribe("datachange_S_KIO_Project")  # 订阅主题
    else:
        _logger.error("Mqtt Bad connection. Code:", rc)


def on_message(mqttc: mqtt, userdata, msg):
    topic = msg.topic
    if topic == "datachange_S_KIO_Project":
        payload = json.loads(msg.payload)
        insert_mplogx_from_king_mqtt(payload, settings.KING_MQTT_OFFSET)


def start_mqtt():
    if settings.MQTT_ENABLED:
        client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2, client_id=settings.BASE_PROJECT_CODE)
        client.on_connect = on_connect
        client.on_message = on_message
        # client.enable_logger(_logger)
        client.connect(host=settings.MQTT_HOST, port=settings.MQTT_PORT)
        client.loop_forever()


if __name__ == "__main__":
    start_mqtt()
