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


def to_hex(message):
    if sys.version_info[0] < 3:
        return message.encode('hex')
    else:
        return message.hex()


class LoraToAwsJob(BaseThread):

    def on_lora_in(self, message):
        json_message = json.loads(message)

        json_message_out = {}
        json_message_out['eui'] = json_message["deveui"]
        json_message_out['type'] = json_message.get('product_id', self.app_context.config.protocol_version)
        json_message_out['rssi'] = json_message["rssi"]
        json_message_out['lsnr'] = json_message["lsnr"]
        json_message_out['payload'] = to_hex(base64.b64decode(json_message['data']))
        # json_message_out['payload'] = "68656c6c6f"

        out_message = json.dumps(json_message_out)

        log.info(
            "Send to SKF Topic: '{}' Message: '{}'".format(
                self.app_context.config.aws_mqtt_config.device_response_topic,
                out_message))
        self.app_context.aws_mqtt.publish(self.app_context.config.aws_mqtt_config.device_request_topic, out_message,
                                          qos=1)

    def incoming_lora_in_message(self, client, userdata, message):
        log.info("Received from MQTT Topic: '{}' Message: '{}' QoS: '{}'".format(message.topic, str(message.payload),
                                                                                 str(message.qos)))
        self.incoming_msg('lora_in', message.payload)

    def init(self, app_context):
        BaseThread.init(self, app_context)
        app_context.local_mqtt.subscribe(self.app_context.config.local_mqtt_config.lora_uplink_topic, 1,
                                         self.incoming_lora_in_message)
