from datetime import datetime

from lxml import etree

def date_to_str(date):
	return datetime.strftime(date, '%Y%m%d')

def str_to_date(string):
	return datetime.strptime(string, '%Y%m%d')

def datetime_to_str(date):
	return datetime.strftime(date, '%Y%m%d%H%M%S')

def str_to_datetime(string):
	return datetime.strptime(string, '%Y%m%d%H%M%S')

def date_operation(date, unit, modifier):
	year = date.year
	month = date.month
	day = date.day

	if unit == 'day':
		day += modifier
	elif unit == 'month':
		month += modifier
	elif unit == 'year':
		year += modifier

	daysinmonth = days_in_month(month, year)
	while day > daysinmonth:
		day -= daysinmonth
		month += 1
		days_in_month(month, year)

	while month > 12:
		month -= 12
		year += 1

	yearstr = str(year)
	monthstr = str(month)
	if len(monthstr) < 2:
		monthstr = "0" + monthstr
	daystr = str(day)
	if len(daystr) < 2:
		daystr = "0" + daystr

	return str_to_date(yearstr + monthstr + daystr)

def days_in_month(month, year):
	if month in [1, 3, 5, 7, 8, 10, 12]:
                return 31
        elif month == 2:
                if is_leap_year(year):
                        return 29
                else:
                        return 28
        else:
                return 30

def is_leap_year(year):
	if year % 400 == 0:
		return True
	elif year % 100 == 0:
		return False
	elif year % 4 == 0:
		return True
	else:
		return False

class TreeRenderer:
        def recursive_tree(self, parent, element):
                if type(element) == dict:
                        child = etree.SubElement(parent, element['kind'], name=element['name'], key=element['key'])
                        if element.has_key('child'):
                                self.recursive_tree(child, element['child'])
                if type(element) == list:
                        for subelement in element:
                                child = etree.SubElement(parent, subelement['kind'], name=subelement['name'], key=subelement['key'])
                                if subelement.has_key('child'):
                                        self.recursive_tree(child, subelement['child'])
                return parent

        def __init__(self, tree):
                self.tree = tree
                self.root = etree.Element(self.tree['kind'], name=self.tree['name'], key=self.tree['key'])
                if self.tree.has_key('child'):
                        element = tree['child']
                        self.root = self.recursive_tree(self.root, element)

        def raw(self):
                return self.tree

        def render(self, format='prettyprint'):
                if format == 'prettyprint':
                        return etree.tostring(self.root, pretty_print=True)
