# -*- coding: utf-8 -*-
from __future__ import division
from .. import _, getSkin, initTimer
from skin import parseColor
from enigma import ePoint, eSize
from Components.Label import Label
from Screens.Screen import Screen
from ..log import logger


class Toast(Screen):
	DURATION_SHORT = 5
	DURATION_MEDIUM = 10
	DURATION_LONG = 30
	DURATION_VERY_LONG = 60

	def __init__(self, session, text, duration, color, toastTimer):
		Screen.__init__(self, session)
		self.skinName = 'E2m3u2b_Toast'
		self.skin = getSkin(self.skinName)
		self.duration = duration
		self.color = color
		self.timer = toastTimer
		self["text"] = Label(text)
		self.onLayoutFinish.append(self._onLayoutFinish)

	def _onLayoutFinish(self):
		orgwidth = self.instance.size().width()
		orgpos = self.instance.position()
		textsize = self["text"].getSize()
		# y size still must be fixed in font stuff...
		textsize = (textsize[0] + 20, textsize[1] + 15)
		self["text"].instance.setZPosition(99)
		self.instance.resize(eSize(*textsize))
		self["text"].instance.resize(eSize(*textsize))
		if self.color:
			self["text"].instance.setForegroundColor(parseColor(self.color))
		# center window
		newwidth = textsize[0]
		self.instance.move(ePoint(orgpos.x() + (orgwidth - newwidth) // 2, orgpos.y()))

class ToastManager(object):
	def __init__(self, session):
		self._session = session
		self._queue = []
		self._deleteQueue = []
		self._currentToast = None
		self._toastTimer, self._toastTimer_conn = initTimer(self._onTimeout)
		self.onClose = lambda: self._toastTimer.stop()

	def showToast(self, text, duration=Toast.DURATION_SHORT, color=None):
		screen = self._session.instantiateDialog(Toast, text, duration, color, self._toastTimer)
		self.show(screen)
		return screen

	def show(self, screen):
		self._queue.append(screen)
		self._processQueue()

	def hide(self, screen):
		if screen == self._currentToast:
			self._onTimeout()
		elif screen in self._queue:
			self._queue.remove(screen)
		else:
			logger.debug("Screen is not a toast or already about to be deleted %s" %(screen,))

	def _onTimeout(self):
		if self._currentToast:
			self._deleteQueue.append(self._currentToast)
			self._currentToast.hide()
			self._currentToast.onHide.append(self._processQueue)
			self._currentToast = None
		self._processQueue()

	def _processQueue(self):
		unfinished = []
		for toast in self._deleteQueue:
			if not toast.timer.isActive():
				# Removing expired toast
				toast.onHide.remove(self._processQueue)
				self._session.deleteDialog(toast)
			else:
				unfinished.append(toast)
		self._deleteQueue = unfinished

		if self._currentToast or not self._queue:
			return
		self._currentToast = self._queue.pop(0)
		self._currentToast.show()
		self._toastTimer.startLongTimer(self._currentToast.duration)
