import sys
import jwt
import re

from log_config.logger import print_log
import config


def endpoint_exists(endpoint, endpoint_list):
    for item in endpoint_list:
        pattern = re.sub(r'{\w+}', r'w+', item)  # Replace path parameters with regex pattern
        if re.match(pattern, endpoint):
            return True
    return False


class JifyMiddleware:

    def auth(self, request):
        print_log('Middleware authentication', request.json['vendor'])
        try:
            if endpoint_exists(request.path, config.BASIC_AUTH_ROUTES):
                if 'HTTP_X_CLIENT_ID' and 'HTTP_X_CLIENT_SECRET' in request.environ:
                    client_id = request.environ['HTTP_X_CLIENT_ID']
                    client_secret = request.environ['HTTP_X_CLIENT_SECRET']
                    if client_id in config.CF_CLIENT_ID and client_secret in config.CF_CLIENT_SECRET:
                        return True
                    else:
                        return False
            return True
        except jwt.ExpiredSignatureError:
            return False
        except jwt.InvalidSignatureError:
            return False
        except Exception as ex:
            print("Exception: " + repr(ex), file=sys.stderr)
            return False

    @staticmethod
    def get_vendor_id(token):
        payload = jwt.decode(token, options={"verify_signature": False})
        return payload['vendor_id']

    @staticmethod
    def verify_jwt(token, key):
        if jwt.decode(token, key, algorithms='HS512'):
            return True
        return False
