#8/22/22 Alex Doherty
#Thermal Printer for Raspberry pi
#Prints the next 24 hours of events from the google calendar


from __future__ import print_function

import datetime
import os.path
import time
import sys

from datetime import date
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']


def main():
    creds = None
    if os.path.exists('/home/pi/PrinterScript/token.json'):
        creds = Credentials.from_authorized_user_file('/home/pi/PrinterScript/token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                '/home/pi/PrinterScript/credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('/home/pi/PrinterScript/token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('calendar', 'v3', credentials=creds)
        # Call the Calendar API
        now = datetime.datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
        
        tomorrow = str(getTomorrow())
        #Gets all events for the rest of the day, into list 'items'
        print('Getting the events for the next 24 hours')
        events_result = service.events().list(calendarId='primary', timeMin=now,
                                              timeMax=tomorrow,
                                              singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])

        if not events:
            print('No upcoming events found.')
            return

        times = []
        names = []
        x = 0
        # Prints the start and name of the events
        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            times.append(str(start[11:16]))
            #print(start, event['summary'])
            names.append(event['summary'])
            x+=1
        #Formats the information into a text file    
        with open('/home/pi/PrinterScript/output.txt', 'w') as f:    
          print('//////////////////', file=f)
          print('//////' + now[5:10] + '///////', file=f)
          for y in range(0,x):
              print (times[y], file=f)
              print ('  ' + str(names[y]), file=f)
              print('', file=f)
          print('//////////////////', file=f)
        os.system("lp /home/pi/PrinterScript/output.txt")        
        

    except HttpError as error:
        print('An error occurred: %s' % error)

main()








