import json
import base64
from SKFClient.core.jobs.base_thread import BaseThread
from SKFClient.core.utils.log import log
from string import Template


class AwsToLoraJob(BaseThread):

    def on_lora_out(self, message):
        json_message = json.loads(message)
        # TODO check payload field name
        json_message["data"] = base64.b64encode(bytearray.fromhex(json_message['payload'])).decode()
        json_message.pop('payload', None)

        # TODO check the topic name after replace template string "loraDownlinkTopic": "lora/$eui/down"
        lora_downlink_topic = Template(self.app_context.config.local_mqtt_config.lora_downlink_topic).safe_substitute(
            json_message)
        json_message.pop('eui', None)

        out_message = json.dumps(json_message)
        log.info("Send to MQTT Topic: '{}' Message: '{}'".format(lora_downlink_topic, str(out_message)))
        self.app_context.local_mqtt.publish(lora_downlink_topic, out_message,
                                            qos=1)

    def incoming_lora_out_message(self, client, userdata, message):
        log.debug("Received message '" + str(message.payload) + "' on topic '"
                  + message.topic + "' with QoS " + str(message.qos))
        log.info("Received from SKF Topic: '{}' Message: '{}' QoS: '{}'".format(message.topic, str(message.payload),
                                                                                 str(message.qos)))
        self.incoming_msg('lora_out', message.payload)

    def init(self, app_context):
        BaseThread.init(self, app_context)
        app_context.aws_mqtt.subscribe(app_context.config.aws_mqtt_config.device_response_topic, 1,
                                       self.incoming_lora_out_message)
