import re
from staff.lib import waffle

from django.http import HttpResponseNotAllowed

from django_replicated.middleware import ReadOnlyMiddleware


class StaffReadOnlyMiddleware(ReadOnlyMiddleware):
    def process_request(self, request):
        readonly_mode = (
            request.META.get('X-READ-ONLY-MODE', 'off').lower() == 'on'
            or (
                waffle.switch_is_active('readonly_mode')
                and not re.match(r'^/admin/waffle.*', request.path)
            )
        )

        if readonly_mode:
            if request.method == 'POST':
                return HttpResponseNotAllowed(['GET'])
            request.service_is_readonly = True
        else:
            super(StaffReadOnlyMiddleware, self).process_request(request)
