#!/usr/bin/env python

# Copyright Ola Ormset 2007 - ola-frontercal@ormset.no
#
# No, this is not GPL. If you want to use this code in your own
# application you must get my permission first.

import SocketServer
import SimpleHTTPServer
import urllib
import urllib2
import time
import sys
import urlparse
import cgi

from xml.dom import minidom

PORT = 7788

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/":
            self.handle_setup()
            return

        try:
            customer, qs = self.path.split("?")
        except:
            customer = self.path
            qs = ""

        if customer == "/add_calendar":
            self.handle_calurl(qs)
            return

        self.handle_getcal(customer,qs)
        
    def handle_getcal(self, customer, qs):
        from_date = time.strftime("%Y-%m-%d", time.localtime(time.time() - 14 * 24 * 60 * 60))
        to_date = time.strftime("%Y-%m-%d", time.localtime(time.time() + 30 * 24 * 60 * 60))
        
        customer = customer.replace(".ics","")
        
        print customer
        print qs
        print self.path
        url = "https://fronter.com" + customer + "/sync/1.0/get_calendar.phtml?" + qs + "&from=%s&to=%s" % (from_date, to_date)

        print self.path, from_date, to_date
        print url
        print

        try:
            fp = urllib2.urlopen(url)
        except:
            return
    
        # Parse the XML and create iCal
        response = self.iCalGenerate(fp)

        self.send_response(200)
        self.wfile.write("\r\n")
        self.wfile.write(response)
        self.wfile.flush()
        return

    def timeconvert(self, isotime):
        return time.strftime("%Y%m%dT%H%M%S", time.strptime(isotime, "%d.%m.%Y %H:%M:%S"))

    def iCalGenerate(self, xmlfp):
        response = ""
        response += "BEGIN:VCALENDAR\n"
        response += "VERSION:2.0\n"
        response += "X-WR-CALNAME:FronterCal\n"
        
        doc = minidom.parse(xmlfp)
        appointments = doc.getElementsByTagName("appointment")
        for app in appointments:
            end = self.timeconvert(app.attributes['end'].value)
            start = self.timeconvert(app.attributes['start'].value)
            s = app.getElementsByTagName("subject")[0].firstChild.data.encode("utf8")
            summary = urllib.unquote_plus(s)
            d = app.getElementsByTagName("subject")[0].firstChild.data.encode("utf8")
            description = urllib.unquote_plus(d)
            response +="BEGIN:VEVENT\n"
            response +="DTSTART:%s\n" % start
            response +="DTEND:%s\n" % end
            response +="SUMMARY:%s\n" % summary
            response +="DESCRIPTION:%s\n" % description
            response +="END:VEVENT\n"

        response +="END:VCALENDAR\n"
        return response

    def handle_setup(self):
        self.send_response(200)
        response = "\r\n"
        response += "<html><head><title>Fronter iCal Proxy Setup</title></head><body>\n"
        response += "<form action='add_calendar' method='GET'><table>"
        response += "<tr><td>Please Type your Fronter Login URL: </td><td><input name='fronterurl' type='text' size='40'></td></tr>"
        response += "<tr><td>Your login name: </td><td><input name='username' type='text'></td></tr>"
        response += "<tr><td>Your login password: </td><td><input name='password' type='text'></td></tr>"
        response += "<tr><td>&nbsp;</td><td><input name='submitted' value='Add calendar' type='submit'></td></tr>"
        response += "</table></form></body></html>"
        self.wfile.write(response)
        return

    def handle_calurl(self, qs):
        self.send_response(200)
        response = "\r\n"

        qs = cgi.parse_qs(qs)
        username = qs['username'][0]
        password = qs['password'][0]
        fronterurl = qs['fronterurl'][0]

        urldata = urlparse.urlparse(fronterurl)

        proto = urldata[0]
        if proto == "http": proto = "https"
        host = urldata[1]
        path = urldata[2]

        self.wfile.write(response)
        return

running = 0
while not running:
    try:
        httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy)
        running = 1
    except:
        PORT += 1
        
print "serving at port", PORT
httpd.serve_forever()
