# -*- coding:utf-8 -*-
"""
@Author  : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc    : some misc
"""
import ssl

import paho.mqtt.client as mqtt

from utils import get_ssl_certificate
from devices.common_model import UserData


def create_mqtt_client(broker_host,
                       broker_port,
                       userdata: UserData,
                       on_message=None,
                       on_connect=None,
                       on_disconnect=None,
                       client_id: str = "",
                       username: str = "",
                       password: str = "",
                       ssl_flag: bool = False):
    if client_id != "":
        client = mqtt.Client(client_id=client_id)
    else:
        client = mqtt.Client()
    client.user_data_set(userdata)
    if on_connect:
        client.on_connect = on_connect
    if on_disconnect:
        client.on_disconnect = on_disconnect
    if on_message:
        client.on_message = on_message
    if ssl_flag:
        ssl_crt = get_ssl_certificate(broker_host, broker_port)
        tls_context = ssl.create_default_context()
        tls_context.verify_mode = ssl.CERT_REQUIRED
        tls_context.load_verify_locations(cadata=ssl_crt)
        try:
            client.tls_set_context(context=tls_context)
            client.tls_insecure_set(False)
        except ValueError:
            pass
    client.username_pw_set(username, password)
    client.connect(broker_host, broker_port)
    return client
