from pathlib import Path
from mastodon import Mastodon

from mastodon_toot_follower import path_util


class App:
    def __init__(self,
                 name: str = 'MastodonTootFollower',
                 url: str = 'https://git.privacy1st.de/langfingaz/MastodonTootFollower',
                 config_dir: Path = None,
                 ):
        if len(name) <= 0:
            raise ValueError(f'name is too short: {name}')
        if config_dir is None:
            config_dir = Path.home().joinpath('.' + name)

        self.name = name
        self.url = url
        self.config_dir = config_dir
        self.mastodon_dict: dict[str, Mastodon] = dict()

        config_dir.mkdir(parents=True, exist_ok=True)
        self._credential_dir().mkdir(parents=True, exist_ok=True)
        self._toot_cache_dir().mkdir(parents=True, exist_ok=True)

    def _get_mastodon(self, mastodon_instance: str) -> Mastodon:
        if mastodon_instance not in self.mastodon_dict:
            self._create_or_load_credentials(mastodon_instance)
            # Create Mastdon API wrapper object.
            self.mastodon_dict[mastodon_instance] = Mastodon(client_id=self._credential_file(mastodon_instance))
        return self.mastodon_dict[mastodon_instance]

    def _create_or_load_credentials(self, mastodon_instance: str) -> None:
        cf = self._credential_file(mastodon_instance)

        # Create application credentials only once and save them.
        if cf.exists():
            return
        Mastodon.create_app(
            client_name=self.name,
            website=self.url,
            api_base_url=mastodon_instance,
            to_file=cf,
            scopes=['read']
        )

    def _credential_file(self, mastodon_instance: str) -> Path:
        return self._credential_dir().joinpath(path_util.escape(mastodon_instance))

    def _credential_dir(self) -> Path:
        return self.config_dir.joinpath('credentials')

    def _toot_cache_dir(self) -> Path:
        return self.config_dir.joinpath('toots')