# Path: code/node/env.py
# NODE_PORT = int(os.environ.get("NODE_PORT", None))
# 
# DATABASE_URL = "http://api/dump/"
# 
# Path: code/node/messages.py
# class Message(object):
#     def __init__(self, type, sequence_no, node):
#         if type is None:
#             type = UNSET
#         # end if
#         assert isinstance(type, int)
#         self.type = type
#         self.sequence_no = sequence_no
#         self.node = node  # i
# 
# 
#     @classmethod
#     def from_dict(cls, data):
#         assert "type" in data
#         type = data["type"]
#         assert type in [UNSET, INIT, LEADER_CHANGE, PROPOSE, PREVOTE, VOTE, ACKNOWLEDGE]
#         if type == INIT:
#             return InitMessage.from_dict(data)
#         # end def
#         if type == LEADER_CHANGE: # pragma: no cover
#             return LeaderChangeMessage.from_dict(data)
#         # end def
#         if type == PROPOSE:
#             return ProposeMessage.from_dict(data)
#         # end def
#         if type == PREVOTE:
#             return PrevoteMessage.from_dict(data)
#         # end def
#         if type == VOTE:
#             return VoteMessage.from_dict(data)
#         # end def
#         if type == ACKNOWLEDGE:
#             return Acknowledge.from_dict(data)
#         # end def
#         return cls(**{
#             "type": data["type"],
#             "sequence_no": data["sequence_no"],
#             "node": data["node"]
#         })
#     # end def
# 
#     def to_dict(self):
#         return {
#             "type": self.type,
#             "sequence_no": self.sequence_no,
#             "node": self.node
#         }
#     # end def
# 
#     def __str__(self):
#         data = self.to_dict()
#         return "{class_name}({values})".format(
#             class_name=self.__class__.__name__,
#             values=", ".join(["{key}={value!r}".format(key=k, value=data[k]) for k in sorted(data)])
#         )
# 
# Path: code/node/todo.py
# def get_sensor_value():
# def timeout():


import socket
    import json
    import requests
from time import sleep
from luckydonaldUtils.logger import logging
from ..env import NODE_PORT, DATABASE_URL
from ..messages import Message
from ..todo import logger
    from ..dockerus import ServiceInfos


def send_message(msg):
    logger.debug(msg)
    assert isinstance(msg, Message)
    data = msg.to_dict()
    data_string = json.dumps(data)
    broadcast(data_string)
    loggert = logging.getLogger("request")
    def print_url(r, *args, **kwargs):
        loggert.info(r.url)
    # end def
    while (True):
        try:
            requests.put(DATABASE_URL, data=data_string, hooks=dict(response=print_url))
            break
        except requests.RequestException as e:
            logger.warning("Failed to report message to db: {e}".format(e=e))
        # end def
        return
# end def


def broadcast(message):
    if not isinstance(message, str):
        raise TypeError("Parameter `message` is not type `str` but {type}: {msg}".format(type=type(message), msg=message))
    hosts = ServiceInfos().other_hostnames()
    # msg = MSG_FORMAT.format(length=len(message), msg=message)
    message += "\n"
    msg = "ANSWER " + str(len(message)) + "\n" + message

# Path: code/node/env.py
# NODE_PORT = int(os.environ.get("NODE_PORT", None))
# 
# DATABASE_URL = "http://api/dump/"
# 
# Path: code/node/messages.py
# class Message(object):
#     def __init__(self, type, sequence_no, node):
#         if type is None:
#             type = UNSET
#         # end if
#         assert isinstance(type, int)
#         self.type = type
#         self.sequence_no = sequence_no
#         self.node = node  # i
# 
# 
#     @classmethod
#     def from_dict(cls, data):
#         assert "type" in data
#         type = data["type"]
#         assert type in [UNSET, INIT, LEADER_CHANGE, PROPOSE, PREVOTE, VOTE, ACKNOWLEDGE]
#         if type == INIT:
#             return InitMessage.from_dict(data)
#         # end def
#         if type == LEADER_CHANGE: # pragma: no cover
#             return LeaderChangeMessage.from_dict(data)
#         # end def
#         if type == PROPOSE:
#             return ProposeMessage.from_dict(data)
#         # end def
#         if type == PREVOTE:
#             return PrevoteMessage.from_dict(data)
#         # end def
#         if type == VOTE:
#             return VoteMessage.from_dict(data)
#         # end def
#         if type == ACKNOWLEDGE:
#             return Acknowledge.from_dict(data)
#         # end def
#         return cls(**{
#             "type": data["type"],
#             "sequence_no": data["sequence_no"],
#             "node": data["node"]
#         })
#     # end def
# 
#     def to_dict(self):
#         return {
#             "type": self.type,
#             "sequence_no": self.sequence_no,
#             "node": self.node
#         }
#     # end def
# 
#     def __str__(self):
#         data = self.to_dict()
#         return "{class_name}({values})".format(
#             class_name=self.__class__.__name__,
#             values=", ".join(["{key}={value!r}".format(key=k, value=data[k]) for k in sorted(data)])
#         )
# 
# Path: code/node/todo.py
# def get_sensor_value():
# def timeout():


# Path: code/node/networks/sender.py
import socket
    import json
    import requests
from time import sleep
from luckydonaldUtils.logger import logging
from ..env import NODE_PORT, DATABASE_URL
from ..messages import Message
from ..todo import logger
    from ..dockerus import ServiceInfos



def send_message(msg):
    logger.debug(msg)
    assert isinstance(msg, Message)
    data = msg.to_dict()
    data_string = json.dumps(data)
    broadcast(data_string)
    loggert = logging.getLogger("request")
    def print_url(r, *args, **kwargs):
        loggert.info(r.url)
    # end def
    while (True):
        try:
            requests.put(DATABASE_URL, data=data_string, hooks=dict(response=print_url))
            break
        except requests.RequestException as e:
            logger.warning("Failed to report message to db: {e}".format(e=e))
        # end def
        return
# end def


def broadcast(message):
    if not isinstance(message, str):
        raise TypeError("Parameter `message` is not type `str` but {type}: {msg}".format(type=type(message), msg=message))
    hosts = ServiceInfos().other_hostnames()
    # msg = MSG_FORMAT.format(length=len(message), msg=message)
    message += "\n"
    msg = "ANSWER " + str(len(message)) + "\n" + message

    logger.debug("Prepared sending to *:{port}:\n{msg}".format(port=NODE_PORT, msg=msg))