import paho.mqtt.client as mqtt
import json
import time
from scripts.config.config_reader import application_config
from scripts.core.GPIO_controller import turn_off
from scripts.util.logger import logger
from scripts.util.file_util import file_write, file_read


def on_connect(client, userdata, flags, rc):
    logger.info("MQTT : Connected with result code " + str(rc))


def on_message(client, userdata, msg):
    motor_status = file_read()
    try:
        payload = msg.payload
        payload = payload.decode('utf-8')
        logger.info('received {} at {}'.format(payload, str(time.time())))
        if 'TriggerMotor' in payload and motor_status['status'] == 'on':
            logger.info('Turning off motor at {}'.format(str(time.time())))
            turn_off()

    except Exception as es:
        logger.error('Exception while fetching data : {}'.format(str(es)))


def live_data():
    try:
        client.connect(host=application_config['mqtt']['host'],
                       port=int(application_config['mqtt']['port']))
        client.subscribe(application_config['mqtt']['topic'])
        client.loop_start()
    except Exception as es:
        logger.error('exception while connection to mqtt : {}'.format(str(es)))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
