# Path: config.py
# def editbatconfig(section,item,itemvalue):
# def loadconfig():


from paho.mqtt import client as mqtt_client
from time import sleep
from config import editbatconfig, config
import logger
  payload=eval(str(message.payload.decode("utf-8")))
  print (payload)
  for section in payload:
    for item in payload[section]:
#      print (section,item,payload[section][item])
      editbatconfig(section,item,payload[section][item])

def on_disconnect(client, userdata, rc):
  if rc:
    log.error('MQTT server disconnect, Restart MQTT')

def connect_mqtt():
  def on_connect(client, userdata, flags, rc):
    if rc == 0:
      print("Connected to MQTT Broker!")
    else:
      fail=f"Failed to connect, return code {rc}"
      print(fail)
      log.error(fail)

  client = mqtt_client.Client(config['mqtt']['clientname'],clean_session=False)
  if config['mqtt']['username']:
    client.username_pw_set(config['mqtt']['username'],config['mqtt']['password'])
  client.on_connect = on_connect
  client.connect(config['mqtt']['brokerip'],config['mqtt']['brokerport'])
  return client

client=connect_mqtt()
client.on_message=on_message
client.on_disconnect=on_disconnect

# Path: config.py
# def editbatconfig(section,item,itemvalue):
# def loadconfig():


# Path: mqtt.py
from paho.mqtt import client as mqtt_client
from time import sleep
from config import editbatconfig, config
import logger

  payload=eval(str(message.payload.decode("utf-8")))
  print (payload)
  for section in payload:
    for item in payload[section]:
#      print (section,item,payload[section][item])
      editbatconfig(section,item,payload[section][item])

def on_disconnect(client, userdata, rc):
  if rc:
    log.error('MQTT server disconnect, Restart MQTT')

def connect_mqtt():
  def on_connect(client, userdata, flags, rc):
    if rc == 0:
      print("Connected to MQTT Broker!")
    else:
      fail=f"Failed to connect, return code {rc}"
      print(fail)
      log.error(fail)

  client = mqtt_client.Client(config['mqtt']['clientname'],clean_session=False)
  if config['mqtt']['username']:
    client.username_pw_set(config['mqtt']['username'],config['mqtt']['password'])
  client.on_connect = on_connect
  client.connect(config['mqtt']['brokerip'],config['mqtt']['brokerport'])
  return client

client=connect_mqtt()
client.on_message=on_message
client.on_disconnect=on_disconnect

client.subscribe(config['mqtt']['subscribetopic'],qos=1)