# -*- coding: utf-8 -*-

from Components.VariableText import VariableText
from Renderer import Renderer

from enigma import eLabel, gFont, eSize

class mtxLabelVariabAO(VariableText, Renderer):
	def __init__(self):
		Renderer.__init__(self)
		VariableText.__init__(self)

		self.textRenderer = None 
		self.fontName = "Regular"
		self.fontSize = 30
		self.fontLimit = 30
		self.maxWidth = 500

	GUI_WIDGET = eLabel

	def connect(self, source):
		Renderer.connect(self, source)

	def postWidgetCreate(self, instance):
		VariableText.postWidgetCreate(self, instance)
		instance.setDefaultAnimationEnabled(False)
		self.textRenderer = eLabel(instance)
		self.textRenderer.resize(eSize(4000, 0))
		self.textRenderer.hide()

	def applySkin(self, desktop, parent):
		attribs = [ ]
		for (attrib, value) in self.skinAttributes:
			if attrib == "size":
				sizeWidth, sizeHeight = value.split(",")
				self.maxWidth = int(sizeWidth)
				attribs.append((attrib,value))
			elif attrib == "font":
				fontName, fontSize = value.split(";")
				self.fontName = fontName
				self.fontSize = int(fontSize)
				attribs.append((attrib,value))
			elif attrib == "fontlimit":
				self.fontLimit = int(value)
			else:
				attribs.append((attrib,value))
		self.skinAttributes = attribs
		flag = Renderer.applySkin(self, desktop, parent)
		self.changed((self.CHANGED_ALL,))
		return flag

	def calcFontHeight(self, text):
		if not self.textRenderer:
			return None
		fontName = self.fontName
		fontSize = self.fontSize
		maxWidth = self.maxWidth
		self.textRenderer.setFont(gFont(fontName, fontSize))
		self.textRenderer.setText(text)
		while True:
			width = self.textRenderer.calculateSize().width()
			print "[mtxLabelVariabAO] font size: %s - width: %s - max width: %s" % (str(fontSize), str(width), str(maxWidth))
			if width < maxWidth:
				break
			else:
				if fontSize > self.fontLimit:
					fontSize -= 2
					self.textRenderer.setFont(gFont(fontName, fontSize))
				else:
					break
		print "[mtxLabelVariabAO] font size final: %s" % str(fontSize)
		return fontSize

	def changed(self, what):
		if what[0] == self.CHANGED_ANIMATED and self.instance:
			return
		elif what[0] == self.CHANGED_CLEAR:
			self.text = ""
		else:
			if self.instance:
				fontSize = self.calcFontHeight(self.source.text.strip()) or self.fontSize
				self.instance.setFont(gFont(self.fontName, fontSize))
			self.text = self.source.text.strip()
			print "[mtxLabelVariabAO] text: %s" % self.text

