from GUIComponent import GUIComponent
from VariableText import VariableText
from os import statvfs

from enigma import eLabel

# TODO: Harddisk.py has similiar functions, but only similiar.
# fix this to use same code
class DiskInfo(VariableText, GUIComponent):
	FREE = 0
	USED = 1
	SIZE = 2
	
	def __init__(self, path, type, update = True):
		GUIComponent.__init__(self)
		VariableText.__init__(self)
		self.type = type
		self.path = path
		if update:
			self.update()

	# Dr.Best --> return filesize with mutable unit
	def formatFileSize(self, size):
		filesize = size
		suffix = ('bytes', 'KB', 'MB', 'GB', 'TB')
		index = 0
		while filesize > 1024:
			filesize = float(filesize) / 1024.0
			index += 1
		filesize_string = "%.2f" % filesize
		if not filesize_string:
			filesize_string = '0'
		return "%s %s" % (filesize_string, suffix[min(index, 4)])
	
	def update(self):
		try:
			stat = statvfs(self.path)
		except OSError:
			return -1
		
		if self.type == self.FREE:
			# Dr.Best --> make the calculation more precisely
			free = stat.f_bavail * stat.f_frsize
			# Dr.Best --> make a nice formated diskfree info
			self.setText("%s %s " %(self.formatFileSize(free), _("free diskspace")))

	GUI_WIDGET = eLabel
