# Path: core/utils/rpla.py
# def get_available_platforms():
#     """
#     This function retrieves the list of available platforms from the Contiki directory.
# 
#     :return: List of strings representing the available platforms
#     """
#     platforms = []
#     for item in listdir(join(CONTIKI_FOLDER, 'platform')):
#         if isdir(join(CONTIKI_FOLDER, 'platform', item)):
#             platforms.append(item)
#     return platforms
# 
# def get_motes_from_simulation(simfile, as_dictionary=True):
#     """
#     This function retrieves motes data from a simulation file (.csc).
# 
#     :param simfile: path to the simulation file
#     :param as_dictionary: flag to indicate that the output has to be formatted as a dictionary
#     :return: the list of motes formatted as dictionaries with 'id', 'x', 'y' and 'motetype_identifier' keys if
#               short is False or a dictionary with each mote id as the key and its tuple (x, y) as the value
#     """
#     motes = []
#     with open(simfile) as f:
#         content = f.read()
#     iterables, fields = [], ['mote_id']
#     for it in ['id', 'x', 'y', 'motetype_identifier']:
#         iterables.append(finditer(r'^\s*<{0}>(?P<{0}>.*)</{0}>\s*$'.format(it), content, MULTILINE))
#     for matches in zip(*iterables):
#         mote = {}
#         for m in matches:
#             mote.update(m.groupdict())
#         motes.append(mote)
#     if as_dictionary:
#         motes = {int(m['id']): (float(m['x']), float(m['y'])) for m in motes}
#     return motes


import networkx
import numpy
from csv import DictReader, DictWriter
from matplotlib import pyplot
from matplotlib.patches import FancyArrowPatch
from os.path import basename, isdir, join, normpath
from re import finditer, match, MULTILINE
from subprocess import Popen, PIPE
from core.utils.rpla import get_available_platforms, get_motes_from_simulation
                time_field = '{}_time'.format(it)
                row[time_field] = float(row[time_field] / 10 ** 6)
            writer.writerow(row)


RELATIONSHIP_REGEX = r'^\d+\s+ID\:(?P<mote_id>\d+)\s+#L\s+(?P<parent_id>\d+)\s+(?P<flag>\d+)$'


def __draw_dodag(path, logger=None):
    """
    This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of
     edges (from ./data/relationships.log).

    :param path: path to the experiment (including [with-|without-malicious])
    :param logger: logging.Logger instance
    """
    if logger:
        logger.debug(" > Drawing DODAG to PNG...")
    pyplot.clf()
    with_malicious = (basename(normpath(path)) == 'with-malicious')
    data, results = join(path, 'data'), join(path, 'results')
    with open(join(data, 'relationships.log')) as f:
        relationships = f.read()
    # first, check if the mote relationships were recorded
    if len(relationships.strip()) == 0:
        if logger:
            logger.warn("Relationships log file is empty !")
        return
    # retrieve motes and their colors
    dodag = networkx.DiGraph()

# Path: core/utils/rpla.py
# def get_available_platforms():
#     """
#     This function retrieves the list of available platforms from the Contiki directory.
# 
#     :return: List of strings representing the available platforms
#     """
#     platforms = []
#     for item in listdir(join(CONTIKI_FOLDER, 'platform')):
#         if isdir(join(CONTIKI_FOLDER, 'platform', item)):
#             platforms.append(item)
#     return platforms
# 
# def get_motes_from_simulation(simfile, as_dictionary=True):
#     """
#     This function retrieves motes data from a simulation file (.csc).
# 
#     :param simfile: path to the simulation file
#     :param as_dictionary: flag to indicate that the output has to be formatted as a dictionary
#     :return: the list of motes formatted as dictionaries with 'id', 'x', 'y' and 'motetype_identifier' keys if
#               short is False or a dictionary with each mote id as the key and its tuple (x, y) as the value
#     """
#     motes = []
#     with open(simfile) as f:
#         content = f.read()
#     iterables, fields = [], ['mote_id']
#     for it in ['id', 'x', 'y', 'motetype_identifier']:
#         iterables.append(finditer(r'^\s*<{0}>(?P<{0}>.*)</{0}>\s*$'.format(it), content, MULTILINE))
#     for matches in zip(*iterables):
#         mote = {}
#         for m in matches:
#             mote.update(m.groupdict())
#         motes.append(mote)
#     if as_dictionary:
#         motes = {int(m['id']): (float(m['x']), float(m['y'])) for m in motes}
#     return motes


# Path: core/utils/parser.py
import networkx
import numpy
from csv import DictReader, DictWriter
from matplotlib import pyplot
from matplotlib.patches import FancyArrowPatch
from os.path import basename, isdir, join, normpath
from re import finditer, match, MULTILINE
from subprocess import Popen, PIPE
from core.utils.rpla import get_available_platforms, get_motes_from_simulation

                time_field = '{}_time'.format(it)
                row[time_field] = float(row[time_field] / 10 ** 6)
            writer.writerow(row)


RELATIONSHIP_REGEX = r'^\d+\s+ID\:(?P<mote_id>\d+)\s+#L\s+(?P<parent_id>\d+)\s+(?P<flag>\d+)$'


def __draw_dodag(path, logger=None):
    """
    This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of
     edges (from ./data/relationships.log).

    :param path: path to the experiment (including [with-|without-malicious])
    :param logger: logging.Logger instance
    """
    if logger:
        logger.debug(" > Drawing DODAG to PNG...")
    pyplot.clf()
    with_malicious = (basename(normpath(path)) == 'with-malicious')
    data, results = join(path, 'data'), join(path, 'results')
    with open(join(data, 'relationships.log')) as f:
        relationships = f.read()
    # first, check if the mote relationships were recorded
    if len(relationships.strip()) == 0:
        if logger:
            logger.warn("Relationships log file is empty !")
        return
    # retrieve motes and their colors
    dodag = networkx.DiGraph()

    motes = get_motes_from_simulation(join(path, 'simulation.csc'))