import json
import time
import socket

from SKFClient.core.jobs.lora_to_aws_job import LoraToAwsJob
from SKFClient.core.utils.log import log
from string import Template

QUEUE_DELETE_CMD = 'packets queue delete $eui'
QUEUE_ADD_CMD = 'packets queue add {"port":1, "deveui": "$eui", "data":"/w=="}'

ONCE_AT_SEC = 300 # 5 min

class LoraToAwsAndBrokerDownJob(LoraToAwsJob):
    def __init__(self):
        LoraToAwsJob.__init__(self)
        self.sending_time = {}

    def on_lora_in(self, message):
        if self.app_context.aws_mqtt.is_connected():
            LoraToAwsJob.on_lora_in(self, message)
        else:
            json_message = json.loads(message)
            cur_epoc_time = int(time.time())
            dev_last_send = self.sending_time.get(json_message["deveui"], cur_epoc_time - ONCE_AT_SEC)
            if dev_last_send <= cur_epoc_time - ONCE_AT_SEC:
                sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                sock.sendto(Template(QUEUE_DELETE_CMD).safe_substitute({"eui": json_message["deveui"]}).encode(), ('127.0.0.1', 6677))
                sock.sendto(Template(QUEUE_ADD_CMD).safe_substitute({"eui": json_message["deveui"]}).encode(), ('127.0.0.1', 6677))
                sock.close()
                log.info("Send reconnect message to device: {}".format(json_message["deveui"]))
                self.sending_time[json_message["deveui"]] = cur_epoc_time
