# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/google/GDoc_File.ipynb.

# %% auto 0
__all__ = ['GoogleDrive_MimeType_Enum', 'GDoc_File', 'GDocFile_DownloadError']

# %% ../../nbs/google/GDoc_File.ipynb 2
import os

from dataclasses import dataclass, field
from enum import Enum
from typing import List

import datetime as dt


from googleapiclient.errors import HttpError

from domolibrary_extensions.utils import (
    upsert_folder,
    convert_str_to_date,
    convert_str_file_name,
    download_zip,
    download_pptx,
)

import domolibrary_extensions.google.auth as ga

from nbdev.showdoc import patch_to

# %% ../../nbs/google/GDoc_File.ipynb 4
class GoogleDrive_MimeType_Enum(Enum):
    """for translating Google Drive types into 'exports as'"""

    docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation"

    odt = "application/vnd.oasis.opendocument.text"
    rtf = "application/rtf"
    pdf = "application/pdf"
    txt = "text/plain"
    zip_file = "application/zip"
    epub = "application/epub+zip"

    folder = "application/vnd.google-apps.folder"
    gdoc = "application/vnd.google-apps.document"
    gsheet = "application/vnd.google-apps.spreadsheet"
    gshortcut = "application/vnd.google-apps.shortcut"
    gslides = "application/vnd.google-apps.presentation"

    # html = 'application/zip'
    # 'tex'  = 'application/zip'
    # 'html.zip'= 'application/zip'

# %% ../../nbs/google/GDoc_File.ipynb 5
download_factory = {
    "application/vnd.google-apps.presentation": {
        "download_fn": download_pptx,
        "export_type": GoogleDrive_MimeType_Enum.pptx,
    },
    "default": {
        "download_fn": download_zip,
        "export_type": GoogleDrive_MimeType_Enum.zip_file,
    },
}

# %% ../../nbs/google/GDoc_File.ipynb 7
@dataclass
class GDoc_File:
    doc_id: str
    doc_name: str
    modified_time: dt.datetime
    url: str

    auth: ga.GoogleAuth = field(repr=False)
    mime_str: str

    mime_type: GoogleDrive_MimeType_Enum = None
    download_factory: dict = None

    parent_ls: List[str] = field(default=None)
    parents: List = field(default=None, repr=False)

    content = None

    def __post_init__(self):
        try:
            self.mime_type = GoogleDrive_MimeType_Enum(self.mime_str).name

        except Exception as e:
            print(e)

        if self.parent_ls:
            self.parents = [
                GDoc_File.get_from_id(document_id=parent, auth=self.auth)
                for parent in self.parent_ls
            ]

    @classmethod
    def _from_json(cls, obj: dict, auth: ga.GoogleAuth, parent_ls: [str] = None):
        return cls(
            mime_str=obj["mimeType"],
            url=obj["webViewLink"],
            doc_id=obj["id"],
            doc_name=obj["name"],
            modified_time=convert_str_to_date(obj["modifiedTime"]),
            parent_ls=parent_ls or obj.get("parents", None),
            auth=auth,
        )

# %% ../../nbs/google/GDoc_File.ipynb 10
@patch_to(GDoc_File, cls_method=True)
def get_from_id(
    cls: GDoc_File,
    document_id: str,
    auth: ga.GoogleAuth = None,
    return_raw: bool = False,
):
    data = (
        auth.service.files()
        .get(
            fileId=document_id,
            fields="id,webViewLink, name, mimeType,modifiedTime,parents ",
        )
        .execute()
    )

    if return_raw:
        return data

    return cls._from_json(obj=data, auth=auth)

# %% ../../nbs/google/GDoc_File.ipynb 13
class GDocFile_DownloadError(Exception):
    def __init__(self, doc_url):
        message = f"failure to download content for {doc_url}"
        super().__init__(message)

# %% ../../nbs/google/GDoc_File.ipynb 14
@patch_to(GDoc_File)
def get_content(self: GDoc_File):
    self.download_factory = download_factory.get(
        self.mime_type, download_factory["default"]
    )

    loop = 0

    while loop < 3 and self.content is None:
        try:
            loop += 1
            self.content = (
                self.auth.service.files()
                .export(
                    fileId=self.doc_id,
                    mimeType=self.download_factory["export_type"].value,
                )
                .execute()
            )

        except HttpError as err:
            print(err)

        except Exception as e:
            print(e)

    if not self.content:
        raise GDocFile_DownloadError(self.webViewLink)

    return self.content

# %% ../../nbs/google/GDoc_File.ipynb 16
@patch_to(GDoc_File)
def download_file(
    self: GDoc_File, output_folder: str = "", is_use_file_id: bool = False
):
    if not self.content:
        self.get_content()

    # create output_folder
    clean_file_name = (
        self.doc_id if is_use_file_id else convert_str_file_name(self.doc_name)
    )

    output_folder_path = os.path.join(output_folder, clean_file_name)
    upsert_folder(output_folder_path)

    return self.download_factory["download_fn"](self.content, output_folder_path)
