#!/usr/bin/env python

"""
This is mostly taken from 
http://code.google.com/apis/calendar/developers_guide_python.html
Google Calendar APIs and Tools - Python developer's guide

there are two ways to authenticate: via a Google Accounts service or programmatically
via Google Accounts:
 - have a page point the user to a special URL generated by GetAuthSubUrl
 - the user comes back to 'next' with a one-time "token=..." parameter (get it with GetAuthSubToken()
 - convert the parameter to a session token and get the calendar service by callingg UpgradeToSession()
via variables:
 - call ProgrammaticLogin with the email and password (cleartext) of the Google account to be accessed
 - use the resulting session
the rest should be self-explanatory
"""

UTCSDIR="/p/lib/python2.6/site-packages"
import sys
import os.path
if os.path.exists(UTCSDIR) and UTCSDIR not in sys.path:
    sys.path.append(UTCSDIR)

try:
    from xml.etree import ElementTree # for Python 2.5 users
except ImportError:
    from elementtree import ElementTree
import gdata.calendar.client
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time
import cgi
import getpass
import urllib
from datetime import datetime

__author__ = "Igor Karpov (ikarpov@cs.utexas.edu)"
__version__ = "1.0.0"
__date__ = "2008/09/09"

def ProgrammaticLogin(email = None, password = None):
    """
    programmatically login to a Google Calendar account and return the 
    authenticated service session
    """
    if not email:
        email = raw_input("Google Calendar account email: ")
    if not password:
        password = getpass.getpass("Google Calendar account password: ")
    client = gdata.calendar.client.CalendarClient(source='edu.utexas.cs.ai-lab.fai.gcal')
    client.ClientLogin(email=email, password=password, source=client.source)
    return client

def PrintAllEventsOnDefaultCalendar(calendar_client):
    feed = calendar_client.GetCalendarEventFeed()
    print 'Events on Primary Calendar: %s' % (feed.title.text,)
    for i, an_event in enumerate(feed.entry):
        print '\t%s. %s' % (i, an_event.title.text,)
        for a_when in an_event.when:
            print '\t    starts: %s' % a_when.start_time
            print '\t    ends: %s' % a_when.end_time

def InsertSingleEvent(calendar_client, calendar=None, title='TEST EVENT',
                      content='TEST CONTENT', where='TEST LOCATION',
                      start_time=None, end_time=None):
    event = gdata.calendar.data.CalendarEventEntry()
    event.title = atom.data.Title(text=title)
    event.content = atom.data.Content(text=content)
    event.where.append(gdata.calendar.data.CalendarWhere(value=where))

    if start_time is None:
        # Use current time for the start_time and have the event last 1 hour
        start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
        end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600))
    event.when.append(gdata.data.When(start=start_time, end=end_time))
    cal = '/calendar/feeds/default/private/full'
    if calendar is not None:
        cal = calendar
    print cal
    new_event = calendar_client.InsertEvent(event, cal)
    return new_event

def SelectCalendar(calendar_client):
    """
    Ask the user which calendar they want to use and return that calendar's URI
    """
    feed = calendar_client.GetOwnCalendarsFeed()
    print feed.title.text
    for i, a_cal in enumerate(feed.entry):
        print '\t%d) %s' % (i, a_cal.title.text)
    c = int(raw_input('Which calendar? '))
    cal = feed.entry[c]
    return cal.content.src

def DateRangeQuery(calendar_client,
                   calendar_id='default',
                   start_date=datetime.today().strftime('%Y-%m-%dT%H:%M:%S.000%Z'),
                   end_date=datetime.today().strftime('%Y-%m-%dT%H:%M:%S.000%Z')):
    query = gdata.calendar.client.CalendarEventQuery(calendar_id, 'private', 'full')
    query.start_min = start_date
    query.start_max = end_date
    feed = calendar_client.CalendarQuery(q=query)
    return feed.entry

def FullTextQuery(calendar_client, calendar_id, text_query):
    query = gdata.calendar.client.CalendarEventQuery(text_query=text_query)
    print calendar_id
    feed = calendar_client.GetCalendarEventFeed(uri=calendar_id, q=query)
    return feed.entry

def Main():
    calendar_client = ProgrammaticLogin()
    #PrintAllEventsOnDefaultCalendar(calendar_client)
    calendar = SelectCalendar(calendar_client)
    InsertSingleEvent(calendar_client, calendar=calendar)

if __name__ == "__main__":
    Main()
