<commit_before>"""
Created on 8 Mar 2019

@author: <NAME> (<EMAIL>)

example:
{"peers": {"scs-bbe-002": {"hostname": "scs-bbe-002", "tag": "scs-be2-2", "shared-secret": "secret1",
"topic": "south-coast-science-dev/production-test/device/alpha-bb-eng-000002/control"}}
"""

from collections import OrderedDict

from scs_core.data.json import JSONable, PersistentJSONable


# --------------------------------------------------------------------------------------------------------------------

class MQTTPeerSet(PersistentJSONable):
    """
    classdocs
    """

    __FILENAME =    "mqtt_peers.json"

    @classmethod
    def persistence_location(cls, host):
        return host.conf_dir(), cls.__FILENAME


    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct_from_jdict(cls, jdict):
        if not jdict:
            return None

        peers = OrderedDict()

        for hostname, item in jdict.get('peers').items():
            peer = MQTTPeer.construct_from_jdict(item)

            peers[hostname] = peer

        return MQTTPeerSet(peers)


    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, peers):
        """
        Constructor
        """
        super().__init__()

        self.__peers = peers                                # dictionary of string: MQTTPeer


    # ----------------------------------------------------------------------------------------------------------------

    def as_json(self):
        jdict = OrderedDict()

        jdict['peers'] = self.__peers

        return jdict


    # ----------------------------------------------------------------------------------------------------------------

    def insert(self, peer):
        # add...
        self.__peers[peer.hostname] = peer

        # sort...
        peers = OrderedDict()

        for hostname in sorted(self.__peers.keys()):
            peers[hostname] = self.__peers[hostname]

        self.__peers = peers


    def remove(self, hostname):
        try:
            del(self.__peers[hostname])

        except KeyError:
            pass


    # ----------------------------------------------------------------------------------------------------------------

    def peer(self, hostname):
        try:
            return self.__peers[hostname]

        except KeyError:
            return None


    @property
    def peers(self):
        return self.__peers.values()


    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        peers = '{' + ', '.join([hostname + ': ' + str(peer) for hostname, peer in self.__peers.items()]) + '}'

        return "MQTTPeerSet:{peers:%s}" % peers


# --------------------------------------------------------------------------------------------------------------------

class MQTTPeer(JSONable):
    """
    classdocs
    """

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct_from_jdict(cls, jdict):
        if not jdict:
            return None

        hostname = jdict.get('hostname')
        tag = jdict.get('tag')
        shared_secret = jdict.get('shared-secret')<commit_msg>Added subset function to MQTTPeerSet.<commit_after>"""
Created on 8 Mar 2019

@author: <NAME> (<EMAIL>)

example:
{"peers": {"scs-bbe-002": {"hostname": "scs-bbe-002", "tag": "scs-be2-2", "shared-secret": "secret1",
"topic": "south-coast-science-dev/production-test/device/alpha-bb-eng-000002/control"}}
"""

from collections import OrderedDict

from scs_core.data.json import JSONable, PersistentJSONable


# --------------------------------------------------------------------------------------------------------------------

class MQTTPeerSet(PersistentJSONable):
    """
    classdocs
    """

    __FILENAME =    "mqtt_peers.json"

    @classmethod
    def persistence_location(cls, host):
        return host.conf_dir(), cls.__FILENAME


    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct_from_jdict(cls, jdict):
        if not jdict:
            return None

        peers = OrderedDict()

        for hostname, item in jdict.get('peers').items():
            peer = MQTTPeer.construct_from_jdict(item)

            peers[hostname] = peer

        return MQTTPeerSet(peers)


    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, peers):
        """
        Constructor
        """
        super().__init__()

        self.__peers = peers                                # dictionary of string: MQTTPeer


    # ----------------------------------------------------------------------------------------------------------------

    def as_json(self):
        jdict = OrderedDict()

        jdict['peers'] = self.__peers

        return jdict


    # ----------------------------------------------------------------------------------------------------------------

    def insert(self, peer):
        # add...
        self.__peers[peer.hostname] = peer

        # sort...
        peers = OrderedDict()

        for hostname in sorted(self.__peers.keys()):
            peers[hostname] = self.__peers[hostname]

        self.__peers = peers


    def remove(self, hostname):
        try:
            del(self.__peers[hostname])

        except KeyError:
            pass


    # ----------------------------------------------------------------------------------------------------------------

    def peer(self, hostname):
        try:
            return self.__peers[hostname]

        except KeyError:
            return None


    def subset(self, hostname_substring):
        subset = []

        for hostname, peer in self.__peers.items():
            if hostname_substring in hostname:
                subset.append(peer)

        return subset


    @property
    def peers(self):
        return self.__peers.values()


    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        peers = '{' + ', '.join([hostname + ': ' + str(peer) for hostname, peer in self.__peers.items()]) + '}'

        return "MQTTPeerSet:{peers:%s}" % peers


# --------------------------------------------------------------------------------------------------------------------

class MQTTPeer(JSONable):
    """
    classdocs
    """

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct_from_jdict(cls, jdict):
        if not jdict:
            return None

        hostname = jdict.get('hostname')
        tag = jdict.get('tag')
        shared_secret = jdict.get('shared-secret')
{'fraction_non_alphanumeric': 0.37540544351995486, 'fraction_numerical': 0.0056409533211112676, 'mean_word_length': 0.9038926174496644, 'pattern_counts': {'":': 12, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3846374', 'n_tokens_mistral': 1713, 'n_tokens_neox': 1579, 'n_words': 329}