import re

from django.conf import settings
from django.http import HttpResponse, HttpResponseServerError

from staff.monitorings.utils import check_host

from staff.lib.middleware.warmup import warmup


class PingMiddleware(object):
    def __init__(self):
        self.db_hosts_to_check = []

        for key in settings.DATABASES:
            if key.startswith('slave') or key == settings.DEFAULT_DB_ALIAS:
                db = settings.DATABASES[key]
                for host in db['HOST'].split(','):
                    self.db_hosts_to_check.append((host, int(db['PORT'])))

    PING_RE = re.compile(r'^/ping/?$')
    PING_DB_RE = re.compile(r'^/ping_db/?$')
    WARMUP_RE = re.compile(r'^/_warmup/?$')

    def process_request(self, request):
        if self.PING_RE.match(request.path):
            return HttpResponse('OK')

        if self.PING_DB_RE.match(request.path):
            for host, port in self.db_hosts_to_check:
                if check_host(host, port):
                    return HttpResponse('OK')

            return HttpResponseServerError('NOTOK')

        if self.WARMUP_RE.match(request.path):
            return HttpResponse(warmup())
