import logging

import requests

from django import forms
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError

from intranet.search.core import storages

log = logging.getLogger(__name__)


def get_service_ticket(dst=None):
    if dst is None:
        dst = settings.ISEARCH['tvm']['clients']['source']['app_id']
    endpoint = settings.ISEARCH['api']['tvm2']
    query = {
        'src': settings.TVM2_CLIENT_NAME,
        'dsts': str(dst),
    }
    url = endpoint['get_service_ticket'].url(query=query)
    headers = {'Authorization': settings.TVM2_AUTH_TOKEN}
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        raise ValueError('Error while getting tvm ticket')
    auth_data = response.json()
    tickets = {value['tvm_id']: value['ticket'] for key, value in auth_data.items()}
    return tickets[int(dst)]


def get_abovemeta_response(type_, query, params, organization):
    url = settings.ISEARCH['abovemeta'][type_].url(query=query)
    kwargs = {}
    headers = {
        'X-REAL-IP': params['ip'],
        settings.TVM2_SERVICE_HEADER: get_service_ticket(),
    }
    if organization:
        headers['X-Org-Id'] = str(organization['directory_id'])
        headers['X-UID'] = str(params['uid'])
        if params.get('cloud_uid'):
            headers['X-Cloud-UID'] = params['cloud_uid']
    else:
        kwargs['cookies'] = params['cookies']

    kwargs = {'headers': headers}
    log.debug('GET abovemeta: %s %s', url, kwargs)
    response = requests.get(url, verify=settings.ISEARCH_CA_CERTS, **kwargs)

    return response


class OrganizationField(forms.CharField):
    """ Поле организации. На вход принимает id директории или label
    и преобразует его в объект организации
    """

    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label', 'Организация (dir_id или label)')
        super().__init__(*args, **kwargs)

    def clean(self, value):
        value = super().clean(value)

        if not value:
            return {}
        org_repository = storages.OrganizationStorage()
        try:
            return org_repository.get_by_directory_or_label(value)
        except ObjectDoesNotExist:
            raise ValidationError('Organization unknown')


class BaseSearchForm(forms.Form):
    text = forms.CharField(label='Запрос', required=False,
                           widget=forms.TextInput(attrs={'class': 'suggest_input'}))
    language = forms.ChoiceField(label='Язык', choices=(('ru', 'ru'), ('en', 'en')))
    organization = OrganizationField(required=False)
    user_uid = forms.CharField(label='User UID', required=False)
    cloud_uid = forms.CharField(label='Cloud uid', required=False)
