import json
import logging

from django.conf import settings

from ids.registry import registry
from ids.exceptions import IDSException


logger = logging.getLogger(__name__)


formatter = registry.get_repository(
    service='formatter',
    resource_type='formatter',
    user_agent='femida',
)


def wiki_format(text, timeout=None, safe=True):
    if not text:
        return ''
    try:
        return formatter.convert_to_html(
            wiki_text=text,
            version=settings.WF_VERSION,
            config='external',
            timeout=timeout or settings.WF_TIMEOUT,
        )
    except Exception as exc:
        logger.exception('Wiki text was not formatted.')
        if safe:
            return ''
        raise exc


def get_diff_in_json(text_a, text_b):
    try:
        diff = formatter.get_diff(text_a, text_b, json=True, version=3)
        return json.loads(diff)
    except (IDSException, ValueError):
        logger.exception('Failed getting diff from WF')
        return ''
