from __future__ import print_function
import os.path
import buildDatabase
import base64
import time
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    #results = service.users().labels().list(userId='me').execute()
    #labels = results.get('labels', [])

    # Query a list of all possible emails
    results = service.users().messages().list(userId='me', maxResults=5, includeSpamTrash=True).execute()
    messages = results.get('messages', [])
    count = 1
    success = 0
    dbHandler = buildDatabase.DatabaseHandler()
    for message in messages:
        print("Working on message " + str(count) + "...")
        count += 1
        key = message.get('id')
        results = service.users().messages().get(userId='me', id=key).execute()
        msg = {}
        # Email Information
        msg['labelIds'] = results.get('labelIds')
        msg['date'] = results.get('internalDate')
        # Payload information
        headers = results.get('payload').get('headers', [])
        msg['from'] = get_header(headers, 'From')
        msg['to'] = get_header(headers, 'To')
        msg['subject'] = get_header(headers, 'Subject')
        if results.get('payload').get('body').get('data') != None:
            msg['body'] = base64.b64decode(results.get('payload').get('body').get('data'))
        else:
            msg['body'] = "Text could not be read"
            success -= 1
        # Upload to the database
        print("Information interpretted:")
        print(msg)
        print("Uploading to database...")
        success += dbHandler.insert(msg)
        time.sleep(5)
    print("Messages stored: " + str(success))

def get_header(headers, name):
    for header in headers:
        if header.get('name') == name:
            return header.get('value')

if __name__ == '__main__':
    main()