import json

from django import http
from django.conf import settings

from intranet.search.core.sources.utils import get_document_url
from intranet.search.api.monitorings.views.utils import request_abovemeta

acl_conf = {
    'isearch': {
        'wiki': {
            'scope': 'wikisearch',
            'url': 'IntranetPoisk/acl-testing/',
            'has_access': 'oauth_acl_testing_has_access',
            'no_access': 'oauth_acl_testing_no_access',
        },
        'tracker': {
            'scope': 'stsearch',
            'url': 'ISEARCHACLMON-1',
            'has_access': 'oauth_acl_testing_has_access',
            'no_access': 'oauth_acl_testing_no_access',
        }
    },
    'bisearch': {
        'wiki': {
            'scope': 'wiki',
            'url': 'search/acl-testing/',
            'has_access': 'oauth_acl_testing_has_access',
            'no_access': 'oauth_acl_testing_no_access',
        },
        'tracker': {
            'scope': 'tracker',
            'url': 'SECRET-1',
            'has_access': 'oauth_acl_testing_has_access',
            'no_access': 'oauth_acl_testing_no_access',
        }
    }
}


def get_request_text(search_url):
    """ Возвращает текст для запроса за acl
    """
    text = 'url:"%s"' % search_url
    return text


def acl_monitoring(request, search):
    conf = acl_conf[settings.APP_NAME][search]

    data = []
    status_code = 200
    search_url = get_document_url(search).format(url=conf['url'])
    text = get_request_text(search_url)

    def format_response(response, message):
        return {'message': message, 'count': response['meta']['count'],
                'docs': [doc['snippet']['url'] for doc in response['results']['docs']]}

    # запрашиваем поиск пользователем, у которого нет доступа
    response = request_abovemeta(text, scope=conf['scope'], token_type=conf['no_access'], robot='da')
    if response['meta']['count'] != 0:
        status_code = 500
        data.append(format_response(response, 'find document by user without privileges'))

    # запрашиваем поиск пользователем, у которого есть доступ
    response = request_abovemeta(text, scope=conf['scope'], token_type=conf['has_access'], robot='da')
    if response['meta']['count'] != 1:
        status_code = 500
        data.append(format_response(response, 'do not find document by user with privileges'))

    return http.HttpResponse(json.dumps(data), content_type='application/json', status=status_code)
