import logging
import time


def driveListFilesQueryWithNextToken(service, parentID, customQuery=None, pageToken=None):
    """Internal function to search items in drive folders

    Args:
        service: Drive service (from getGoogleServices()['drive'])
        parentID (str): Drive folder ID of parent where to search
        customQuery (str): optional custom query parameters
        pageToken (str): optional page token for paging results of large sets

    Returns:
        Tuple (items, nextPageToken) containing the items found and pageToken to retrieve
        remaining data
    """
    param = {}
    param['q'] = "'" + parentID + "' in parents and trashed = False"
    if customQuery:
        param['q'] += " and " + customQuery
    param['fields'] = 'nextPageToken, files(id, name)'
    param['pageToken'] = pageToken
    param['supportsTeamDrives'] = True
    param['includeTeamDriveItems'] = True
    # print(param)
    retriesLeft = 5
    while retriesLeft > 0:
        retriesLeft -= 1
        try:
            results = service.files().list(**param).execute()
            items = results.get('files', [])
            nextPageToken = results.get('nextPageToken')
            # print('Files: ', items)
            return (items, nextPageToken)
        except Exception as e:
            logging.warning('Error listing drive. %d retries left. %s', retriesLeft, str(e))
            if retriesLeft > 0:
                time.sleep(5) # wait 5 seconds before retrying
    logging.error('Too many list failures')
    return None