import requests
from functools import wraps
import json
from flask import request


def authorized(handler):
    @wraps(handler)
    def authorize(*args, **kwargs):
        from util.util import Util
        from exceptions import CustomException, AuthenticationException
        import os
        arrivy_base_url = os.getenv('ARRIVY_BASE_URL')

        headers = Util.generate_headers_for_arrivy_from_request(request)

        url = arrivy_base_url + '/api/task_routes/route_optimization/authorize'
        data = dict()

        if request.method == 'POST':
            if headers.get('Content-Type') == 'application/json':
                if request.get_json().get('company_id'):
                    data['company_id'] = request.get_json().get(
                        'company_id')
            elif headers.get('Content-Type') == 'application/x-www-form-urlencoded':
                if request.form.get('company_id'):
                    data['company_id'] = request.form.get('company_id')
        elif request.method == 'GET':
            query_params = dict(request.args)
            url += '?' + \
                '&'.join([f'{key}={value}' for key,
                          value in query_params.items()])
            for key, value in query_params.items():
                data[key] = value

        try:
            response = requests.post(url=url, headers=headers, data=data)
            if response.status_code == 200:
                return handler(auth_info=response.json(), *args, **kwargs)
            return response.json(), response.status_code
        except requests.RequestException as e:
            raise AuthenticationException(e)
        except requests.ConnectionError as e:
            raise AuthenticationException(e)
        except requests.HTTPError as e:
            raise AuthenticationException(e)
        except requests.Timeout as e:
            raise AuthenticationException(e)
        except requests.TooManyRedirects as e:
            raise AuthenticationException(e)
        except requests.URLRequired as e:
            raise AuthenticationException(e)
        except Exception as e:
            raise e

    # Renaming the function name:
    # authorize.__name__ = handler.__name__
    return authorize
