#!/usr/bin/python3

import psutil

class Load:
    def __init__(self):
        """dont look at me im hiddouse"""
        self.processor_load = psutil.cpu_percent()
        self.memory = psutil.virtual_memory().percent
        self.processor_freq = psutil.cpu_freq().current
        self.swap_mem = psutil.swap_memory()[3]

        dick = psutil.sensors_temperatures()
        for sensor_list in dick.values():
            self.processor_temp = int(sensor_list[0][1])

        pi = psutil.disk_io_counters(perdisk=True)
        disk_list = []
        for dinger in pi.items():
            disk_list.append(dinger)
        self.read_difference = 0
        self.write = disk_list[16][1][3]
        self.write_count = disk_list[16][1][1]
        self.write_difference = 0
        self.delay = 0
        self.process_list()
        
        self.new_read = 0
        self.read= 0
        self.write = 0
        self.new_write = 0
        for each in disk_list:
            self.read += each[1][2]
            self.write += each[1][3]

    def load_update(self):
        """updates the cpu information"""
        self.processor_load = psutil.cpu_percent()
        self.memory = psutil.virtual_memory().percent
        self.swap_mem = psutil.swap_memory()[3]
        dick = psutil.sensors_temperatures()
        
        self.process_list()

        for sensor_list in dick.values():
            self.processor_temp = int(sensor_list[0][1])
        
        self.processor_freq = int(psutil.cpu_freq().current)
        self._disk_magik()

    def _disk_magik(self):
        """helper method to handle disk info, its so magical its magik"""
        pi = psutil.disk_io_counters(perdisk=True)
        disk_list = []
        
        for dinger in pi.items():
            disk_list.append(dinger)
        
        for each in disk_list:
            self.new_read += each[1][2]
            self.new_write += each[1][3]
        
        if self.new_read > self.read:
            self.read_difference = round(((self.new_read - self.read) / 1000000), 1)
            self.read = self.new_read
        elif self.new_write > self.write:
            self.write_difference = round(((self.new_write - self.write) / 1000000), 1)
            self.write = self.new_write
        else:
            self.delay += 1
            if self.delay >= 6:
                self.read_difference = 0
                self.write_difference = 0
                self.delay = 0
        self.new_read = 0
        self.new_write = 0
       


    def getListOfProcessSortedByMemory(self):
        '''
        Get list of running process sorted by Memory Usage
        '''
        listOfProcObjects = []
        # Iterate over the list
        for proc in psutil.process_iter():
            try:
                # Fetch process details as dict
                pinfo = proc.as_dict(attrs=['pid', 'name', 'username'])
                #pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)
                pinfo['cpu'] = proc.cpu_percent()
                # Append dict to list
                listOfProcObjects.append(pinfo);
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass
        # Sort list of dict by key vms i.e. memory usage
        listOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['cpu'], reverse=True)
        return listOfProcObjects
    def process_list(self):
        self.listOfRunningProcess = self.getListOfProcessSortedByMemory()
        #for elem in listOfRunningProcess[:5] :
        #    print(f"name: {elem['name']} pid: {elem['pid']} cpu usages: {elem['cpu']}")
    
    
    def processor_update(self):
        self.processor_load = psutil.cpu_percent()
        self.processor_freq = int(psutil.cpu_freq().current)
