from .service import get_service
from googleapiclient.errors import HttpError
import io
from googleapiclient.http import MediaIoBaseDownload

def download_file(file_id: str):
    """
    Download a file from Google Drive.
    Supports both binary files and Google Docs editor files. Basically there are separate ways to download the binary files like
    images and other Google Docs files.

    Args:
        file_id (str): The Drive file ID.

    Returns:
        bytes: The file content in bytes, or None if failed.
                It returns the file content in bytes, and you have to create appropriate file and add that content in it.
                That means if you are downloading docs than create a xlsx file and add the content in it.

                Like:
                    with open("output_file.xlsx", "wb") as f:
                        f.write(data)
    
    Example:
        ```python
        def test_download_file():
            try:
                data = download_file(
                    file_id= '126-Qh-8mCCWjdma1D4sdQpfgvEk_kQr6FxrwmnGrDZA'
                )
                if data:
                    with open("output_file.xlsx", "wb") as f:
                        f.write(data)
                return f'Test case passed: {data}'
            except Exception as e:
                return f'Error while Downloading file: {e}'
        ```
    """
    try:
        service = get_service(service_name="drive")
        file_metadata = service.files().get(fileId=file_id, fields="mimeType, name").execute()
        mime_type = file_metadata.get("mimeType")
        file_name = file_metadata.get("name")
        file = io.BytesIO()

        if mime_type.startswith("application/vnd.google-apps"):
            export_mime_types = {
                "application/vnd.google-apps.document": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/vnd.google-apps.spreadsheet": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "application/vnd.google-apps.presentation": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                "application/vnd.google-apps.drawing": "image/png",
            }
            export_mime = export_mime_types.get(mime_type, "application/pdf")
            response = service.files().export_media(fileId=file_id, mimeType=export_mime)
        else:
            response = service.files().get_media(fileId=file_id)
        downloader = MediaIoBaseDownload(file, response)
        done = False
        while not done:
            status, done = downloader.next_chunk()
        return file.getvalue()
    except HttpError as error:
        return error

def delete_file(file_id: str) -> str:
    """
    To delete the file from the Google Drive.

    Args:
        file_id (str): ID of the file to be deleted.

    Returns:
        str: Confirmation of the deletion of the file from the Google Drive.
    
    Example:
        ```python
        def test_delete_file():
            try:
                data = delete_file(
                    file_id= '126-Qh-8mCCWjdmd1D4sdQpfgvEk_kQr6FxrwmnGrDZA'
                )
                return f'Test case passed: {data}'
            except Exception as e:
                return f'Error while Deleting the file: {e}'

        ```
    """
    try:
        service= get_service(service_name= 'drive')
        service.files().delete(fileId= file_id).execute()
        return f"File {file_id} deleted successfully."
    except HttpError as error:
        return error

def create_folder(folder_name: str) -> dict:
    """
    To create the folder in the Google Drive.

    Args:
        folder_name (str): Name of the folder to be created.

    Returns:
        dict: Dictionary having folder ID. Like: {'id': '1pUwhqaXuvHKQiq3_RGqVrPpAIE7VkLU4'}
    
    Example:
        ```python
        def test_create_folder():
            try:
                insertion = create_folder(
                    folder_name= "Test"
                )
                return f'Test case passed: {insertion}'
            except Exception as e:
                return f'Error while Folder Creation: {e}'
        ```
    """
    try:
        service= get_service(service_name= "drive")
        metadata= {
            "name": folder_name,
            "mimeType": "application/vnd.google-apps.folder"
        }
        folder= service.files().create(body=metadata, fields= "id").execute()
        return folder
    except HttpError as error:
        return {"Error" : error}