import re
import urllib.parse

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage

from .models import Definition

RE_HANGUL = re.compile(r'[(]*[\uAC00-\uD7AF]+[\uAC00-\uD7AF (),;]*', re.IGNORECASE)


def index(request):
    definitions = Definition.objects.all()
    limit = request.GET.get('limit')
    try:
        limit = int(limit)
    except (ValueError, TypeError):
        limit = 15
    paginator = Paginator(definitions, limit)
    page = request.GET.get('page')
    try:
        show_lines = paginator.page(page)
    except PageNotAnInteger:
        show_lines = paginator.page(1)
    except EmptyPage:
        show_lines = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'definitions': definitions,
                                          'lines': show_lines})


def fix_definition_format(definition):
    definition = definition.replace('{I}', '<i>') \
                           .replace('{/I}', '</i>') \
                        .replace('{B}', '<b>') \
                        .replace('{/B}', '</b>') \
                        .replace('{Pr}', '[') \
                        .replace('{/Pr}', ']') \
                        .replace('{H}', '') \
                        .replace('{/H}', '') \
                        .replace('{E}', '') \
                        .replace('{/E}', '') \
                        .replace('{J}', '') \
                        .replace('{/J}', '') \
                        .replace('{S}', '') \
                        .replace('{/S}', '') \
                        .replace('{U}', '') \
                        .replace('{-}', '- ')
    if definition.startswith('&'):
        definition = definition[1:]
    word, _definition = definition.split('\n', 1)
    definition = '<h4>' + word + '</h4>\n'
    definition += _definition
    return definition


def generate_translate_tag(word):
    out = '<a href="https://translate.google.de/#ko/en/{word_url}" '
    out += 'title="Translate with Google Translate" target="'
    out += '_blank">{word}</a>'
    out = out.format(word_url=urllib.parse.quote_plus(word.group(0)),
                    word=word.group(0))
    return out


def get_definitions(request):
    if request.is_ajax():
        q = request.GET.get('term', '')
        definitions = Definition.objects.filter(word__icontains=q) \
                                        .values_list('word', flat=True)[:25]
        data = list(definitions)
    else:
        data = []
    return JsonResponse(data, safe=False)


def get_definition(request, id):
    definition = get_object_or_404(Definition, id=id)
    data = fix_definition_format(definition.definition)
    data = RE_HANGUL.sub(generate_translate_tag, data)
    return HttpResponse(data)


def get_definition_word(request, word):
    definition = get_object_or_404(Definition, word=word)
    data = fix_definition_format(definition.definition)
    data = RE_HANGUL.sub(generate_translate_tag, data)
    return HttpResponse(data)
[((10, 12, 10, 83), 're.compile', 're.compile', ({(10, 23, 10, 67): '"""[(]*[\\\\uAC00-\\\\uD7AF]+[\\\\uAC00-\\\\uD7AF (),;]*"""', (10, 69, 10, 82): 're.IGNORECASE'}, {}), "('[(]*[\\\\uAC00-\\\\uD7AF]+[\\\\uAC00-\\\\uD7AF (),;]*', re.IGNORECASE)", False, 'import re\n'), ((20, 16, 20, 45), 'django.core.paginator.Paginator', 'Paginator', ({(20, 26, 20, 37): 'definitions', (20, 39, 20, 44): 'limit'}, {}), '(definitions, limit)', False, 'from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\n'), ((28, 11, 29, 63), 'django.shortcuts.render', 'render', ({(28, 18, 28, 25): 'request', (28, 27, 28, 39): '"""index.html"""', (28, 41, 29, 62): "{'definitions': definitions, 'lines': show_lines}"}, {}), "(request, 'index.html', {'definitions': definitions, 'lines': show_lines}\n    )", False, 'from django.shortcuts import render, get_object_or_404\n'), ((74, 11, 74, 41), 'django.http.JsonResponse', 'JsonResponse', (), '', False, 'from django.http import HttpResponse, JsonResponse\n'), ((78, 17, 78, 53), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (), '', False, 'from django.shortcuts import render, get_object_or_404\n'), ((81, 11, 81, 29), 'django.http.HttpResponse', 'HttpResponse', ({(81, 24, 81, 28): 'data'}, {}), '(data)', False, 'from django.http import HttpResponse, JsonResponse\n'), ((85, 17, 85, 57), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (), '', False, 'from django.shortcuts import render, get_object_or_404\n'), ((88, 11, 88, 29), 'django.http.HttpResponse', 'HttpResponse', ({(88, 24, 88, 28): 'data'}, {}), '(data)', False, 'from django.http import HttpResponse, JsonResponse\n')]