import logging
import requests

from constance import config
from django.conf import settings

from intranet.femida.src.utils.tvm2_client import get_service_tickets


logger = logging.getLogger(__name__)


class TikaiteError(Exception):
    pass


class NotParsedError(TikaiteError):
    pass


class UnsupportedMediaTypeError(TikaiteError):
    pass


def extract_text(mds_path, mimetype):
    tvm_tickets = get_service_tickets(
        settings.TVM_APE_CLIENT_ID,
        settings.TVM_TIKAITE_CLIENT_ID,
    )
    headers = {
        'X-Srw-Key-Type': 'MDS',
        'X-Srw-Namespace': 'femida',
        'X-Srw-Key': mds_path,
        'X-Ya-Service-Ticket': tvm_tickets.get(settings.TVM_APE_CLIENT_ID),
        'X-Srw-Service-Ticket': tvm_tickets.get(settings.TVM_TIKAITE_CLIENT_ID),
    }
    params = {
        'stid': '{namespace}/{path}'.format(namespace=settings.MDS_NAMESPACE, path=mds_path),
        'mimetype': mimetype,
        # 'limit': 640000,
    }
    url = 'http://{host}/disk/handler/'.format(host=settings.TIKAITE_HOST)
    try:
        response = requests.get(
            url=url,
            params=params,
            headers=headers,
            timeout=config.TIKAITE_TIMEOUT,
        )
    except requests.RequestException:
        logger.exception('Failed request to tikaite for `%s`', mds_path)
        raise TikaiteError

    if not response.ok:
        logger.error('Bad status code (%s) from tikaite for `%s`', response.status_code, mds_path)
        if response.status_code == 415:
            raise UnsupportedMediaTypeError
        raise TikaiteError

    try:
        data = response.json()
    except ValueError:
        logger.exception('Invalid JSON in tikaite response for `%s`', mds_path)
        raise TikaiteError

    if data['parsed'] is False:
        logger.exception('Failed to parse text for `%s`', mds_path)
        raise NotParsedError

    try:
        text = data['body_text']
    except KeyError:
        logger.exception('There is not `body_text` in tikaite response for `%s`', mds_path)
        raise TikaiteError

    return text
