import os
import sys
from app.libraries.setup import Setup
from mastodon import Mastodon
from mastodon.Mastodon import MastodonNotFoundError, MastodonNetworkError, MastodonReadTimeout, MastodonAPIError, MastodonUnauthorizedError, MastodonIllegalArgumentError
import requests
import pdb

class DomainBlocks():

    name = 'Domain blocks for Mastodon'

    def __init__(self, mastodon_hostname=None, domain_block_api=None, session=None):

        self.domain_blocks_api = '/api/v1/admin/domain_blocks'
        setup = Setup()
        self.mastodon_hostname = setup.mastodon_hostname 
        self.mastodon_app_token = { 'Authorization': 'Bearer %s'%setup.mastodon_app_token }

        if session:
            self.session = session
        else:
            self.session = requests.Session()

    def domain_blocks_create(self, server, priv_comment, pub_comment):

        data = {
                'domain': server,
                'severity': 'suspend',
                'reject_media': 'true',
                'reject_reports': 'true',
                'private_comment': priv_comment,
                'public_comment': pub_comment,
                'obfuscate': 'true',
                }
        
        endpoint = f'https://{self.mastodon_hostname}/{self.domain_blocks_api}'
        
        response = self.__api_request('POST', endpoint, data)

        if response.ok:

            print(f"Done, {server} is now suspended")

        else:

            pass

    def __api_request(self, method, endpoint, data={}):

        response = None

        try:

            kwargs = dict(data=data)

            response = self.session.request(method, url = endpoint, headers = self.mastodon_app_token, **kwargs)

        except Exception as e:

            raise MastodonNetworkError(f"Could not complete request: {e}")

        if response is None:

            raise MastodonIllegalArgumentError("Illegal request.")

        if not response.ok:

                try:
                    if isinstance(response, dict) and 'error' in response:
                        error_msg = response['error']
                    elif isinstance(response, str):
                        error_msg = response
                    else:
                        error_msg = None
                except ValueError:
                    error_msg = None

                if response.status_code == 404:
                    ex_type = MastodonNotFoundError
                    if not error_msg:
                        error_msg = 'Endpoint not found.'
                        # this is for compatibility with older versions
                        # which raised MastodonAPIError('Endpoint not found.')
                        # on any 404
                elif response.status_code == 401:
                    ex_type = MastodonUnauthorizedError
                elif response.status_code == 422:
                    return response
                elif response.status_code == 500:
                    ex_type = MastodonInternalServerError
                elif response.status_code == 502:
                    ex_type = MastodonBadGatewayError
                elif response.status_code == 503:
                    ex_type = MastodonServiceUnavailableError
                elif response.status_code == 504:
                    ex_type = MastodonGatewayTimeoutError
                elif response.status_code >= 500 and \
                    response.status_code <= 511:
                    ex_type = MastodonServerError
                else:
                    ex_type = MastodonAPIError

                raise ex_type(
                    'Mastodon API returned error',
                    response.status_code,
                    response.reason,
                    error_msg)

        else:

            return response


