# 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
                   '-e', 'wpan.dst64',
                   '-e', 'icmpv6.type',
                   '-e', 'ipv6.src',
                   '-e', 'ipv6.dst',
                   '-e', 'icmpv6.code',
                   '-e', 'data.data',
                   '-r', join(data, 'output.pcap')], stdout=PIPE)
        out, _ = p.communicate()
    except OSError:
        out = b"Tshark is not installed !"
        if logger:
            logger.warn(out)
    with open(join(results, 'pcap.csv'), 'wb') as f:
        f.write(out)


PT_ITEMS = ['monitored', 'on', 'tx', 'rx', 'int']
PT_REGEX = r'^({})_(?P<mote_id>\d+) {} (?P<{}>\d+)'


def __convert_powertracker_log_to_csv(path, logger=None):
    """
    This function creates a CSV file (to ./results) from a PowerTracker log file (from ./data).
    This is inspired from https://github.com/sieben/makesense/blob/master/makesense/parser.py.

    :param path: path to the experiment (including [with-|without-malicious])
    :param logger: logging.Logger instance
    """
    if logger:
        logger.debug(" > Converting power tracking log to CSV...")

# 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

                   '-e', 'wpan.dst64',
                   '-e', 'icmpv6.type',
                   '-e', 'ipv6.src',
                   '-e', 'ipv6.dst',
                   '-e', 'icmpv6.code',
                   '-e', 'data.data',
                   '-r', join(data, 'output.pcap')], stdout=PIPE)
        out, _ = p.communicate()
    except OSError:
        out = b"Tshark is not installed !"
        if logger:
            logger.warn(out)
    with open(join(results, 'pcap.csv'), 'wb') as f:
        f.write(out)


PT_ITEMS = ['monitored', 'on', 'tx', 'rx', 'int']
PT_REGEX = r'^({})_(?P<mote_id>\d+) {} (?P<{}>\d+)'


def __convert_powertracker_log_to_csv(path, logger=None):
    """
    This function creates a CSV file (to ./results) from a PowerTracker log file (from ./data).
    This is inspired from https://github.com/sieben/makesense/blob/master/makesense/parser.py.

    :param path: path to the experiment (including [with-|without-malicious])
    :param logger: logging.Logger instance
    """
    if logger:
        logger.debug(" > Converting power tracking log to CSV...")

    platforms = [p.capitalize() for p in get_available_platforms()]