# -*- coding: iso-8859-1 -*-
"""
   Some comments....
"""
Dependencies = []
import os,string,Image,StringIO
from MoinMoin import config, wikiutil, version
from MoinMoin.PageEditor import PageEditor
from MoinMoin import user, util
from MoinMoin.Page import Page
from MoinMoin.action import AttachFile
from MoinMoin.formatter.text_html import Formatter
from MoinMoin.parser import wiki
from MoinMoin.util import MoinMoinNoFooter, pysupport
from datetime import datetime, timedelta, date, time
from icalendar import Calendar, Event, UTC, Alarm

from types import TupleType, ListType
SequenceTypes = [TupleType, ListType]
import re
from string import atoi


action_name = __name__.split('.')[-1]

def execute(pagename, request):
    if not request.user.may.read(pagename):
        Page(request, pagename).send_page(request)
        return
    
    _ = request.getText
    
    debug = True
    
    page = Page(request, pagename)
    text = page.get_raw_body()
    
    request.http_headers(["Content-type: text/plain;charset=%s" % config.charset])
    
    try:
        alarm_minutes = int(request.form.get('alarm', [-1])[0])
    except ValueError:
        alarm_minutes = -1
    
    lines = re.findall('[^\n]+',text)
    
    cal = Calendar()
    cal.add('prodid', '-//My calendar product//mxm.dk//')
    cal.add('version', '2.0')
    
    errors = []
    
    for line in lines:
        if re.match('^#',line) != None:
            continue
        if debug:
            request.write('line=',line,'\n')
        words = re.findall('[^\s]+',line)
        indesc = False # remember when we have entered the description part of the line
        d1 = '-1'
        m1 = '-1'
        y1 = '-1'
        d2 = '-1'
        m2 = '-1'
        y2 = '-1'
        h1 = '-1'
        min1 = '-1'
        h2 = '-1'
        min2 = '-1'
        hasEnd = False
        hasTime = False
        hasDate = False
        summary = ''
        delta = None
        weekday = '' # if set -> weekly recurrence
        for word in words:
            if debug:
                request.write('  word="',word,'"\n')
                request.write('indesc=')
                if indesc:
                    request.write('True')
                else:
                    request.write('False')
                request.write('\n')
            if indesc == False:
                if word == 'Mondays':
                    weekday = 'MO'
                elif word == 'Tuesdays':
                    weekday = 'TU'
                elif word == 'Wednesdays':
                    weekday = 'WE'
                elif word == 'Thursdays':
                    weekday = 'TH'
                elif word == 'Fridays':
                    weekday = 'FR'
                elif word == 'Saturdays':
                    weekday = 'SA'
                elif word == 'Sundays':
                    weekday = 'SU'
                # dates...
                elif re.match('^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,4}$',word) != None:
                    if debug:
                        request.write('matched DD.MM.YYYY\n')
                    d1,m1,y1 = re.findall('[0-9]+',word)
                    hasEnd = False
                    delta = timedelta(1)
                elif re.match('^[0-9]{1,2}\.{0,1}-[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,4}$',word) != None:
                    if debug:
                        request.write('matched DD-DD.MM.YYYY\n')
                    d1,d2,m1,y1 = re.findall('[0-9]+',word)
                    m2 = m1
                    y2 = y1
                    hasEnd = True
                    delta = timedelta(1)
                    indesc = True # don't allow time definition
                elif re.match('^[0-9]{1,2}\.[0-9]{1,2}\.{0,1}-[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,4}$',word) != None:
                    if debug:
                        request.write('matched DD.MM-DD.MM.YYYY\n')
                    d1,m1,d2,m2,y1 = re.findall('[0-9]+',word)
                    y2 = y1
                    hasEnd = True
                    delta = timedelta(1)
                    indesc = True # don't allow time definition
                elif re.match('^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,4}-[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,4}$',word) != None:
                    if debug:
                        request.write('matched DD.MM.YYYY-DD.MM.YYYY\n')
                    d1,m1,y1,d2,m2,y2 = re.findall('[0-9]+',word)
                    hasEnd = True
                    delta = timedelta(1)
                    indesc = True # don't allow time definition
                # times...
                elif re.match('^[0-9]{1,2}:[0-9]{1,2}$',word) != None:
                    if debug:
                        request.write('matched HH:MM\n')
                    h1,min1 = re.findall('[0-9]+',word)
                    hasEnd = False
                    hasTime = True
                    delta = timedelta(0,3600) # def evt len = 1h if time of day is given
                elif re.match('^[0-9]{1,2}:[0-9]{1,2}-[0-9]{1,2}:[0-9]{1,2}$',word) != None:
                    if debug:
                        request.write('matched HH:MM-HH:MM\n')
                    h1,min1,h2,min2 = re.findall('[0-9]+',word)
                    y2 = y1
                    m2 = m1
                    d2 = d1
                    hasEnd = True
                    indesc = True
                    hasTime = True
                    delta = None
                elif hasTime and re.match('^[0-9]+m$',word) != None:
                    if debug:
                        request.write('matched m\n')
                    mins = re.findall('[0-9]+',word)[0]
                    mins = atoi(mins) * 60
                    delta = timedelta(0,mins)
                    hasEnd = False
                    indesc = True
                elif hasTime and re.match('^[0-9]+h$',word) != None:
                    if debug:
                        request.write('matched h\n')
                    h = re.findall('[0-9]+',word)[0]
                    delta = timedelta(0,atoi(h)*3600)
                    hasEnd = False
                    indesc = True
                else:
                    indesc = True
                    summary += word
            else:
                if len(summary)>0:
                    summary += ' '
                summary += word
        if debug:
            request.write('d1=',d1,', m1=',m1,', y1=',y1,', summary=',summary,'\n')
            request.write('h1=',h1,', min1=',min1,'\n')
            request.write('d2=',d2,', m2=',m2,', y2=',y2,'\n')
            request.write('h2=',h2,', min2=',min2,', weekday=',weekday,'\n')
            request.write('hasTime=')
            if hasTime:
                request.write('True')
            else:
                request.write('False')
            request.write('\n')
            request.write('hasEnd=')
            if hasEnd:
                request.write('True')
            else:
                request.write('False')
            request.write('\n')
            request.write('delta')
            if delta == None:
                request.write('==None')
            else:
                request.write('!=None')
            request.write('\n')
        event = Event()
        event.add('summary', summary)
        #event.add('description', text)
        startdate = None
        enddate = None
        starttime = None
        endtime = None
        start = None
        end = None
        if d1 != '-1':
            d1 = atoi(d1)
            m1 = atoi(m1)
            y1 = atoi(y1)
            if y1 < 2000:
                y1 += 2000
            startdate = date(y1,m1,d1)
        if d2 != '-1':
            d2 = atoi(d2)
            m2 = atoi(m2)
            y2 = atoi(y2)
            if y2 < 2000:
                y2 += 2000
            enddate = date(y2,m2,d2)
        if min1 == '-1':
            min1 = '0'
        if h1 != '-1':
            h1 = atoi(h1)
            min1 = atoi(min1)
            starttime = time(h1,min1,tzinfo=UTC)
        if min2 == '-1':
            min2 = '0'
        if h2 != '-1':
            h2 = atoi(h2)
            min2 = atoi(min2)
            endtime = time(h2,min2,tzinfo=UTC)
        if weekday == '': # no recurrency
            if startdate == None:
                errors += line
                continue
            elif starttime == None:
                start = startdate
            else:
                start = datetime.combine(startdate,starttime)
            if endtime == None:
                end = enddate
            else:
                end = datetime.combine(enddate,endtime)
            if end == None:
                end = start
            if delta != None:
                end += delta
            event.add('dtstart', start)
            event.add('dtend', end)
            event.add('dtstamp', start)
        else: # weekly recurrency
            # when to start recurrences? (also includes starting time of event)
            if startdate == None:
                startdate = date.today() - timedelta(7) # no date -> run along...
            if starttime == None:
                start = startdate
            else:
                start = datetime.combine(startdate,starttime)
            # when to stop recurrences? (no time)
            if enddate == None:
                until = date.today() + timedelta(84)
            else:
                until = enddate
            # end of each event, NOT end of recurrence!
            if endtime == None:
                end = start
            else:
                end = datetime.combine(startdate,endtime)
            if delta != None:
                end += delta
            r = dict(freq='WEEKLY', interval=1, byday=weekday)
            r['UNTIL'] = until;
            event.add('rrule',r)
            event.add('dtstart', start)
            event.add('dtend', end)
            event.add('dtstamp', start)
        if alarm_minutes >= 0:
            alarm = Alarm()
            alarm.add('description', '')
            alarm.add('action', 'DISPLAY')
            if hasTime:
                alarm.add('trigger', start-timedelta(0,alarm_minutes*60))
            else:
                #alarm.add('trigger', datetime.combine(start,time())-timedelta(0,18*3600))
                alarm.add('trigger', start-timedelta(1))
            event.add_component(alarm)
        #event['uid'] = '20050115T101010/27346262376@mxm.dk'
        event.add('priority', 5)
        cal.add_component(event)
        
    # wrap error message in event *g*
    errdesc = ''
    for line in errors:
        if errdesc != '':
            errdesc += '\n'
        errdesc += line
    if len(errors)>0:
        errdesc = 'The following lines contain errors:\n\n' + errdesc
        event = Event()
        event.add('summary', 'IcsProducer Errors')
        event.add('description', errdesc)
        event.add('dtstart', datetime.utcnow())
        event.add('dtend', datetime.utcnow() + timedelta(0,10800))
        event.add('dtstamp', datetime.utcnow())
        event.add('priority', 5)
        cal.add_component(event)
    
    request.write(cal.as_string())
    raise MoinMoinNoFooter

