import json
import logging
import sys

import redis
from rivr.http import Request, Response

from palaverapi.responses import ProblemResponse
from palaverapi.views.push import redis_client


def handle_error(request: Request, exception: Exception):
    logger = logging.getLogger('rivr.request')
    logger.error(exception, exc_info=sys.exc_info())
    return ProblemResponse(500, 'Internal Server Error')


def is_redis_available() -> bool:
    try:
        redis_client.ping()
    except redis.exceptions.ConnectionError:
        return False

    return True


def index(request: Request) -> Response:
    return Response(status=204)


def status(request) -> Response:
    if is_redis_available:
        return Response(
            json.dumps(
                {
                    'status': 'pass',
                }
            ),
            content_type='application/health+json',
        )

    return Response(
        json.dumps(
            {
                'status': 'fail',
            }
        ),
        status=504,
        content_type='application/health+json',
    )


def crash(request: Request) -> Response:
    raise RuntimeError("You are eaten by a grue")

@@ -86,16 +86,55 @@
 sponse%0A%0A
+from palaverapi.models import database%0A
 from pal
@@ -596,16 +596,172 @@
  True%0A%0A%0A
+def is_database_available() -%3E bool:%0A    try:%0A        database.connect()%0A    except Exception:%0A        return False%0A%0A    database.close()%0A    return True%0A%0A%0A
 def inde
@@ -885,16 +885,42 @@
 vailable
+ and is_database_available
 :%0A      

include db availability in healthcheck