# -*- coding: utf-8 -*-
#  Coded by Gemini-Team
from Converter import Converter
from time import localtime
from Components.Element import cached

from Plugins.Bp.geminimain.gTools import dayStr, dayStrSmall, monthStr, monthStrSmall

#Beispiel fuer type
#DD.MM.YY - 20.01.11
#MM.DD YYYY - 01.20 2011
#DD.MMM.YYYY - 20.Jan.2011
#NNN DD.MMMM.YYYY Mon 20.Januar.2011

class DateToText(Converter, object):
	DATE_N = 0
	DATE_D = 1
	DATE_M = 2
	DATE_Y = 3
	
	def __init__(self, type):
		Converter.__init__(self, type)
		format = type
		self.__seperator = []
		self.__formatlist = [[0,0,self.DATE_N,""],[0,0,self.DATE_D,""],[0,0,self.DATE_M,""],[0,0,self.DATE_Y,""]]
		pos = 1
		seperatorstr = ""
		for x in range(len(format)):
			if format[x] == 'N':
				self.__formatlist[self.DATE_N][0] +=1
				self.__formatlist[self.DATE_N][1] = pos
				if seperatorstr != "":
					pos += 1
					self.__seperator.append(seperatorstr)
					seperatorstr = ""
			elif format[x] == 'D':
				self.__formatlist[self.DATE_D][0] +=1
				self.__formatlist[self.DATE_D][1] = pos
				if seperatorstr != "":
					pos += 1
					self.__seperator.append(seperatorstr)
					seperatorstr = ""
			elif format[x] == 'M':
				self.__formatlist[self.DATE_M][0] +=1
				self.__formatlist[self.DATE_M][1] = pos
				if seperatorstr != "":
					pos += 1
					self.__seperator.append(seperatorstr)
					seperatorstr = ""
			elif format[x] == 'Y':
				self.__formatlist[self.DATE_Y][0] +=1
				self.__formatlist[self.DATE_Y][1] = pos
				if seperatorstr != "":
					pos += 1
					self.__seperator.append(seperatorstr)
					seperatorstr = ""
			else:
				seperatorstr += format[x]
		self.__formatlist = sorted(self.__formatlist, key=lambda x:(x[1]), reverse=False)

	@cached
	def getText(self):
		try:
			time = self.source.time
			if time is None:
				return ""
			mytime = localtime(time)
		
			for x in self.__formatlist:
				if x[1] == 0:
					continue
				if x[2] == self.DATE_D:
					if x[0] == 2:
						x[3] = "%02d" % mytime.tm_mday
					else:
						x[3] = "%d" % mytime.tm_mday
				elif x[2] == self.DATE_Y:
					if x[0] > 2:
						x[3] = "%d" % mytime.tm_year
					else:
						x[3] = "%d" % (mytime.tm_year-2000)
				elif x[2] == self.DATE_M:
					if x[0] == 2:
						x[3] = "%02d" % mytime.tm_mon
					elif x[0] == 3:
						x[3] = monthStrSmall[mytime.tm_mon-1]
					elif x[0] == 4:
						x[3] = monthStr[mytime.tm_mon-1]
					else:
						x[3] = "%d" % mytime.tm_mon
				elif x[2] == self.DATE_N:
					if x[0] < 4:
						x[3] = dayStrSmall[mytime.tm_wday]
					else:
						x[3] = dayStr[mytime.tm_wday]

			retstr=""
			sep=0
			for x in self.__formatlist:
				if x[1] == 0:
					continue
				retstr += x[3]
				if sep < len(self.__seperator):
					retstr += self.__seperator[sep]
					sep +=1
				else:
					retstr += " "
			return retstr
		except:
			pass
		return "???"

	text = property(getText)
