#!/usr/bin/python3
import sys
import yaml
from oauth2client import client
from googleapiclient import sample_tools
from datetime import datetime

def main(argv):
    with open("secrets.yml", "r") as secrets_file:
        secrets = yaml.load(secrets_file)
    # Authenticate and construct service.
    service, flags = sample_tools.init(
        [], 'calendar', 'v3', __doc__, __file__,
        scope='https://www.googleapis.com/auth/calendar')

    calendar_id = secrets["calendarId"]
    task_name = argv[1]
    project = argv[2]
    start_date = datetime.strftime(datetime.now(), "%Y-%m-%dT%H:%M:%S")
    due_date = argv[3]
    task_id = argv[4]

    try:
        task_body = {
          "summary": project + ": " + task_name,
          "start": {
            "timeZone": secrets["timezone"],
            "dateTime": start_date
          },
          "end": {
            "timeZone": secrets["timezone"],
            "dateTime": due_date
          },
          "id": task_id
        }

        req = service.events().insert(
        calendarId = calendar_id,
        body = task_body
        )

        req.execute()


    except client.AccessTokenRefreshError:
        print('The credentials have been revoked or expired, please re-run'
              'the application to re-authorize.')

if __name__ == '__main__':
    main(sys.argv)
