#!/usr/bin/python3

import subprocess
import time
import threading
from window import Network_Traffic


class Network_Temple:
    def __init__(self):
        self.network = ''
        self.test = []

        self.network_traffic = Network_Traffic()

    def display(self):
        #self.network_traffic = Network_Traffic()
        self.network_traffic.run_network()
        
        '''
        while True:
            
            network_non_doubles = [x for x in self.test if x not in network_non_doubles]
            for network in network_non_doubles:
                network = network.replace('\n', '')
                print(network)
            print('done')
            #print(self.test)
            self.test = []
            time.sleep(2)
        '''

    def network_load(self):
        network_load = subprocess.Popen(["sudo", "nethogs", "-t"], stdout=subprocess.PIPE, universal_newlines=True)
        for stdout_line in iter(network_load.stdout.readline, ""):
            self.__create_list(stdout_line)

    def __create_list(self, network_stdout):
        if 'Refreshing' in network_stdout:
            self.network_traffic.display_activity.prep_message(self.test)
            self.test = []
        else:
            self.test.append(network_stdout)

"""
network_list = stdout_line.split('\n')

for network in network_list:
    if network == '':
        pass
    elif 'Refreshing' not in network and 'unknown' not in network:
    #else:
    #print(network)
    process_list = network.split(' ')
    #self.network = process_list
    #print(process_list[0], process_list[-1].lstrip('\t'))
    #inlet_outlet = process_list[-1].split('\t')
    #if len(inlet_outlet) > 2:
    #    print(f'process:{process_list[0]} in:{inlet_outlet[1]}, out:{inlet_outlet[2]}')
"""

network_temple = Network_Temple()
network_thread = threading.Thread(target = network_temple.network_load, name = 'network')
display_thread = threading.Thread(target = network_temple.display, name = 'display')
network_thread.start()
display_thread.start()
network_thread.join()
display_thread.join()
