import pathlib

from . import core

## \brief A <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path">standard Path object</a> pointing to where the user's local storage is.
#  
#  Exactly where this is depends on your operating system:
#  - On Windows, this is defined as `%%APPDATA%\seagull`, which typically evaluates to something like `"C:\Users\YourNameHere\AppData\Roaming\seagull"`
#  - On MacOS, this is defined as `~/Library/Application Support/seagull`, where ~ is your home directory.
#  - On Linux, this is defined as `~/.local/share/seagull`.
#  \note On Linux, the XDG specification for defining alternative data directories is not currently respected. This will likely change in a future version.
path_storagedir = pathlib.Path()

## \internal
#  \brief Defines JavaScript API functions for pywebview.
class JS_API:
    #  \brief Whether or not we're in debug mode.
    debug_mode = False

    def __init__(self, debug_mode=False):
        self.debug_mode = debug_mode

    ## \brief Loads data stored under a specific "key" in the local filesystem.
    #  \param key The key to load.
    #  \return File contents, or `None`.
    #  In the current implementation, key is just a raw filename loaded relative to path_storagedir,
    #  which is calculated as part of main thread startup.
    def load_data(self, key):
        if not (path_storagedir / key).exists():
            return None

        with open(path_storagedir / key) as fd_datafile:
            try:
                return fd_datafile.read()
            except Exception as exc:
                core.log.error(f"problem loading {key} (from {path_storagedir}): {exc}")
                return None
    
    ## \brief Saves data stored under a specific "key" in the local filesystem.
    #  \param key The key to save to.
    #  \param data The data to write.
    #  In the current implementation, key is just a raw filename loaded relative to path_storagedir,
    #  which is calculated as part of main thread startup.
    def save_data(self, key, data):
        with open(path_storagedir / key, "w") as fd_datafile:
            try:
                fd_datafile.write(data)
            except Exception as exc:
                core.log.error(f"problem saving {key} (to {path_storagedir}): {exc}")

    ## \brief Deletes all data stored at key.
    #  \param key The key to delete.
    def delete_data(self, key):
        if (path_storagedir / key).exists():
            (path_storagedir / key).unlink()

api = JS_API()