import os
import sys
from datetime import datetime
import pytz
from mastodon import Mastodon
from mastodon.Mastodon import MastodonMalformedEventError, MastodonNetworkError, MastodonReadTimeout, MastodonAPIError, MastodonIllegalArgumentError
import pdb

class Setup():

    name = 'fediverse setup'

    def __init__(self, config_file=None, mastodon_hostname=None, peers_api=None, user_agent=None, secrets_filepath=None, mastodon_app_token=None):

        self.config_file = "config/config.txt"
        self.mastodon_hostname = self.__get_parameter("mastodon_hostname", self.config_file)
        self.peers_api = '/api/v1/instance/peers?'
        self.user_agent = {'User-agent': "fediverse's stats"}

        self.secrets_filepath = 'secrets/secrets.txt'

        is_setup = self.__check_mastodon_setup(self)

        if is_setup:

            self.mastodon_app_token = self.__get_mastodon_parameter("mastodon_app_token", self.secrets_filepath)

        else:

            self.mastodon_app_token = self.mastodon_setup(self)

    @staticmethod
    def __check_mastodon_setup(self):

        is_setup = False

        if not os.path.isfile(self.secrets_filepath):
            print(f"File {self.secrets_filepath} not found, running setup.")
        else:
            is_setup = True

        return is_setup

    @staticmethod
    def mastodon_setup(self):

        if not os.path.exists('secrets'):
            os.makedirs('secrets')

        self.mastodon_user = input("Mastodon user login? ")
        self.mastodon_password = input("Mastodon user password? ")
        self.app_name = 'fediverse'

        self.mastodon_app_token = self.mastodon_log_in()

        if not os.path.exists(self.secrets_filepath):
            with open(self.secrets_filepath, 'w'): pass
            print(f"{self.secrets_filepath} created!")

        with open(self.secrets_filepath, 'a') as the_file:
            print("Writing Mastodon parameters to " + self.secrets_filepath)
            the_file.write(f'mastodon_app_token: {self.mastodon_app_token}')

        return self.mastodon_app_token

    def mastodon_log_in(self):

        token = ''

        try:

            response = Mastodon.create_app(
                self.app_name,
                scopes=["read","write"],
                to_file=None,
                api_base_url=self.mastodon_hostname
                )
            client_id = response[0]
            client_secret = response[1]

            mastodon = Mastodon(client_id = client_id, client_secret = client_secret, api_base_url = self.mastodon_hostname)
        
            token = mastodon.log_in(
                self.mastodon_user,
                self.mastodon_password,
                scopes = ["read", "write"],
                to_file = None
            )

            print('Log in succesful!')

        except MastodonIllegalArgumentError as i_error:

            sys.stdout.write(f'\n{str(i_error)}\n')

        except MastodonNetworkError as n_error:

            sys.stdout.write(f'\n{str(n_error)}\n')

        except MastodonReadTimeout as r_error:

            sys.stdout.write(f'\n{str(r_error)}\n')

        except MastodonAPIError as a_error:

            sys.stdout.write(f'\n{str(a_error)}\n')

        finally:

            return token

    def __get_parameter(self, parameter, config_file):

        if not os.path.isfile(config_file):
            print(f"File {config_file} not found..")

            self.mastodon_hostname = input("\nMastodon hostname: ")

            self.__create_config(self)
            self.__write_config(self)

        with open( self.config_file ) as f:
            for line in f:
                if line.startswith( parameter ):
                    return line.replace(parameter + ":", "").strip()

    def __get_mastodon_parameter(self, parameter, secrets_filepath):

        if not os.path.isfile(secrets_filepath):
            print(f"File {secrets_filepath} not found..")

            self.sign_in()

        with open( self.secrets_filepath ) as f:
            for line in f:
                if line.startswith( parameter ):
                    return line.replace(parameter + ":", "").strip()

    @staticmethod
    def __create_config(self):

        if not os.path.exists('config'):

            os.makedirs('config')

        if not os.path.exists(self.config_file):

            print(self.config_file + " created!")
            with open(self.config_file, 'w'): pass

    @staticmethod
    def __write_config(self):

        with open(self.config_file, 'a') as the_file:

            the_file.write(f'mastodon_hostname: {self.mastodon_hostname}')
            print(f"adding parameters to {self.config_file}\n")
