# Imports
from flask import Blueprint, render_template
from os import getenv as env
import logging

import src.routes.snake as snake


# Create blueprint
bp = Blueprint(
    'error_handlers',
    __name__,
    template_folder=env('TEMPLATE_FOLDER', default='../templates'),
    static_folder=env('STATIC_FOLDER', default='../static')
)


# Create logger
log = logging.getLogger(__name__)


# Route for 500 error
@bp.route('/500')
@bp.app_errorhandler(500)
def internal_server_error(error=None):
    if error is not None:
        log.error("Internal server error: %s", error)
    return render_template('errors/500.html'), 500


# Route for 404 error
@bp.route('/404')
@bp.app_errorhandler(404)
def not_found(error=None):
    if error is not None:
        log.warning("Page not found: %s", error)
    scores = snake.get_leaderboard()
    token = snake.generate_start_token()
    return render_template('errors/404.html', scores=scores, token=token, cap_key=env('CAP_KEY', default='')), 404 if error is not None else 200


# Route for 400 error
@bp.route('/400')
@bp.app_errorhandler(400)
def bad_request(error=None):
    if error is not None:
        log.warning("Bad request: %s", error)
    return render_template('errors/400.html', error=error), 400