import datetime
import json
import requests

from django import http
from django.conf import settings
from django.utils import timezone

from intranet.search.core import storages


def get_required_revisions():
    required_revisions = {}
    for search_name, search_data in settings.ISEARCH['searches']['base'].items():
        required_revisions[search_name] = search_data.get('required_revisions') or []
    return required_revisions


def set_error(errors, service, index, organization):
    if organization['id'] not in errors:
        errors[organization['id']] = {
            'id': organization['id'],
            'label': organization['label'],
            'directory_id': organization['directory_id'],
            'services': {},
        }

    error = errors[organization['id']]
    if service not in error['services']:
        error['services'][service] = []
    error['services'][service].append(index)


def create_response(errors):
    status_code = requests.codes.OK
    response_data = {'status': 'OK'}

    if errors:
        status_code = requests.codes.INTERNAL_SERVER_ERROR
        response_data['status'] = 'Revisions not found'
        response_data['failed_organizations'] = list(errors.values())
        response_data['failed_organizations_count'] = len(errors)

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


def active_revision_check(request):
    org_storage = storages.OrganizationStorage()

    required_revisions = get_required_revisions()
    valid_indexation_timeout = datetime.timedelta(hours=settings.ISEARCH_VALID_INDEXATION_TIMEOUT)
    active_date = timezone.now() - valid_indexation_timeout

    errors = {}
    for service, indexes in required_revisions.items():
        for index in indexes:
            failed_organizations = org_storage.get_revision_failed(service, index, active_date)
            for organization in failed_organizations:
                set_error(errors, service, index, organization)

    return create_response(errors)
