"""
This module parses the log generated by nethogs and prints
the total data sent and received in kb.
"""

import sys,os
from .monitor import Monitor
import pandas as pd

class NethogsParser(Monitor):
    def __init__(self, dir, rank, refresh, cmd):
        super().__init__(dir, rank, refresh)
        self.raw_path = os.path.join(self.dir, f"nethogs_raw_{self.rank}.log")
        self.csv_path = os.path.join(self.dir, f"nethogs_{self.rank}.csv")
        self.exe_path = self._exe_path(cmd.split()[0])

    def mointor_cmd(self, command):
        raise Exception("Monitor using launch not implemented for nethogs")

    def monitor_pid(self, pid):
        print(f"MONITORING WITH NETHOGS on pid={pid}")
        self._launch(f"nethogs -t -d {self.refresh}".split(), stdout=self.raw_path)

    def parse(self):
        print("PARSING NETHOGS")
        with open(self.raw_path, 'r') as raw_log:
            log = []
            lines = raw_log.readlines()
            for idx,line in enumerate(lines):
                if line.startswith("Refreshing"):
                    line_set = False
                    for app_line in lines[idx:]:
                        if self.exe_path in app_line:
                            app_line = app_line.split("\t")
                            log.append([float(app_line[1]), float(app_line[2].replace("\n", ""))])
                            line_set = True
                            break
                    if not line_set:
                        log.append([0,0])

        df = pd.DataFrame(log, columns=['sent', 'received'])
        df.to_csv(self.csv_path, index=False)
