#!/usr/bin/env python
# Copyright (c) 2013 Cedric Bosdonnat <cedric.bosdonnat@free.fr>
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
#     The above copyright notice and this permission notice shall be included in
#     all copies or substantial portions of the Software.
# 
#     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#     THE SOFTWARE.

import email
import sys
import os.path
import caldav
from caldav.elements import dav

def find_or_create_calendar( principal, client, url, name ):
    calendars = principal.calendars()
    calendar = None
    for item in calendars:
        try:
            if item.get_properties( dav.DisplayName() ) == name:
                calendar = item
                break;
        except TypeError:
            # in some cases, we may have empty names throwing an exception
            pass

    if calendar == None:
        calendar = caldav.Calendar( client, url, principal, ).save( )
    return calendar

def get_uid_from_ical( ical ):
    uid = None
    lines = ical.splitlines()
    for line in lines:
        if line.startswith( "UID:" ):
            uid = line[4:]
    return uid


def push_event( vcal, url, calendar_name, calendar_segment ):
    client = caldav.DAVClient( url )
    principal = caldav.Principal( client, url )
    calendar = find_or_create_calendar( principal, client, url + calendar_segment, calendar_name )
    uid = get_uid_from_ical( vcal )
    if ( uid  != None ):
        event = calendar.event( uid )
    if ( event == None ):
        event = caldav.Event( client, data = vcal, parent = calendar )
    else:
        event.data = vcal
    event.save( )

def get_event_from_multipart( mail ):
    event = None
    for part in mail.get_payload( ):
        if part.is_multipart( ):
            event = get_event_from_multipart( part )
        else:
            if part.get_content_type( ).startswith( 'text/calendar' ):
                # We got the ical part of the multipart!
                event = part.get_payload()
    return event


def main():
    mailStr = ""
    for line in sys.stdin:
        mailStr += line

    # Get the options
    if ( len( sys.argv ) != 4 ):
        return

    url = sys.argv[1]
    calendar_segment = sys.argv[2]
    calendar_name = sys.argv[3]

    if mailStr != "":
        mail = email.message_from_string( mailStr )
        if mail.is_multipart( ):
            event = get_event_from_multipart( mail )
            if event != None:
                # We got the ical part of the multipart!
                push_event( event, url, calendar_name, calendar_segment )


if __name__ == "__main__":
    main()
