#!/usr/bin/env python3

from time import sleep
from math import floor
from shutil import get_terminal_size
import sys, signal

__version__ = '0.1.0'

sec_names = [
	'user',
	'nice',
	'system',
	'idle',
	'iowait',
	'irq',
	'softirq',
	'steal',
	'guest',
	'guest_nice'
]

list_idle = [
	'idle',
	'iowait'
]

list_busy = [
	'user',
	'nice',
	'system',
	'irq',
	'softirq',
	'steal',
	'guest',
	'guest_nice'
]

def assign(values, names):
	data = {}
	try:
		for i, name in enumerate(names):
			data[name] = values[i]
	except KeyError:pass
	return data

def only(values, include):
	data = {}
	for key, val in values.items():
		if key in include:
			data[key] = val
	return data

def total(values):
	total = 0
	for val in values:
		total += val
	return total

def delta(values):
	return values[1]-values[0]

class ProgBar:
	def __init__(self, width, full_chars=[chr(255)], partial_chars=['1','2','3','4']):
		self.width = width
		self.full_chars = full_chars
		self.partial_chars = partial_chars

	def get(self, prog: float) -> str:
		full = int(self.width * prog)

		full_str = ''
		for i in range(full):
			full_str += self.full_chars[i % len(self.full_chars)]

		full_str = f'{full_str:<{self.width}}'
		return full_str

def read_proc():
	with open('/proc/stat') as f:
		data = {}
		for line in f:
			line = line.replace('\n', '')
			if not line.startswith('cpu'):
				continue

			cpu_split = line.split()
			cpu = cpu_split[0]
			cpu_info = cpu_split[1:]

			cpu_parsed = assign(cpu_info,sec_names)
			for key, num in cpu_parsed.items():
				cpu_parsed[key] = int(num)
			cpu_busy_list = only(cpu_parsed,list_busy)
			cpu_busy = total(cpu_busy_list.values())
			cpu_idle_list = only(cpu_parsed,list_idle)
			cpu_idle = total(cpu_idle_list.values())

			data[cpu] = [cpu_busy, cpu_idle]

	return data

def cleanup(*args):
	print('\033[?1049l\033[?25h', end='')
	exit(0)

def main():
	signal.signal(signal.SIGTERM, cleanup)
	try:
		print('\033[?1049h\033[H\033[2J\033[?25l', end='')
		bar = ProgBar(7)
		current = read_proc()
		while True:
			sleep(3)
			width, height = (20,4)
			print('\033[H', end='')
			previous = current
			current = read_proc()
			strlist = []
			for cpu, data in current.items():
				if cpu == 'cpu':continue
				busy1, idle1 = tuple(previous[cpu])
				busy2, idle2 = tuple(current[cpu])
				busy = busy2-busy1
				idle = idle2-idle1
				total = busy + idle
				usage = busy / total
				strlist.append(f'{cpu}: {floor(usage*100)}%\033[K')
			print('\n'.join(strlist), end='')

	except KeyboardInterrupt:pass
	finally:
		cleanup()

if __name__ == '__main__':
	main()
