# 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
log = logger.logging.getLogger(__name__)
log.setLevel(logger.logging.DEBUG)
log.addHandler(logger.errfile)


def on_message(client,userata,message):
  """Executed when any subscribed MQTT message arives
  At present assumes payload is item to change in battery.config
  makes change and rewrites config file"""

  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)


# 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

log = logger.logging.getLogger(__name__)
log.setLevel(logger.logging.DEBUG)
log.addHandler(logger.errfile)


def on_message(client,userata,message):
  """Executed when any subscribed MQTT message arives
  At present assumes payload is item to change in battery.config
  makes change and rewrites config file"""

  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)