from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from apiclient import errors


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


def delete_file(service, file_id):
    """Permanently delete a file, skipping the trash.

    Args:
    service: Drive API service instance.
    file_id: ID of the file to delete.
    """
    try:
        service.files().delete(fileId=file_id).execute()
        print("File ID {} is deleted".format(file_id))
    except errors.HttpError as error:
        print('An error occurred: %s' % error)


def upload_file(name, parents, service):
    """
    Upload file
    :param name: Input name of file, and
    :param parents: folder id of destination folder
    :param service: Drive API service instance.
    :return:
    """
    file = {'name': name, 'parents': parents}
    # Input path of source file
    media = MediaFileUpload('./output/combined_usafacts.csv')
    file = service.files().create(body=file, fields='id', media_body=media).execute()
    print('Upload suscessful for File ID: %s' % file.get('id'))


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)
    return service


if __name__ == '__main__':
    service = main()
    name = 'combined_usafacts.csv'  # file name
    parents = ['1qS15m3_gbaKhKlpyp42bgJhDZhr7Sq_B']  # Folder id

    # Search for file and delete it
    response = service.files().list(q="name='{}'".format(name) + " and modifiedTime > '2020-11-19T12:00:00' and trashed = false",
                                          spaces='drive',
                                          fields='nextPageToken, files(id, name)',
                                          pageToken=None).execute()
    if len(response['files']) > 0:
        file_id = response['files'][0]['id']
        delete_file(service, file_id)

    upload_file(name, parents, service)