ajax_lexeme_view.py 30.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
# -*- coding: utf-8 -*-
import datetime

from django.core.cache import cache
from django.shortcuts import get_object_or_404
from django.utils.encoding import force_unicode
from django.utils.translation import ugettext as _
from django.db.models import Max

from dictionary.ajax_lexeme_slickgrid import LexemeQuery
from dictionary.auto_derivatives import lexeme_derivatives, create_derivative
from dictionary.models import Lexeme, LexemeInflectionPattern, PartOfSpeech, \
    Pattern, Vocabulary, Qualifier, prepare_table, ClassificationValue, \
    CrossReference, InputLexeme, CrossReferenceType, editable_vocabularies, \
    visible_qualifiers, LexemeAttributeValue, Gender, LexemeAttribute, \
    LexemeAV, LexemeCV, visible_vocabularies, LexemeList, filter_visible, Ending
from dictionary.forms import LexemeEditForm, LIPEditForm, ClassificationForm, \
    CrossReferenceForm, ActionFieldForm, ACTION_FIELDS,\
    LexemeOpenAttributeForm, LexemeClosedAttributeForm, \
    LexemeMultipleAttributeForm
from common.decorators import ajax, AjaxError, render_ajax
from common.util import error_messages, bisect_left, format_date


@render_ajax(
    template='inflection_tables.html', method='get', login_required=False)
def inflection_tables(request, variant, lexeme_id):
    try:
        lexeme = Lexeme.all_objects.get(pk=lexeme_id)  # może być nowy
    except Lexeme.DoesNotExist:
        raise AjaxError('access denied')
    if not lexeme.perm(request.user, 'view'):
        raise AjaxError('access denied')
    qualifiers = visible_qualifiers(request.user)
    tables = lexeme.inflection_tables(variant, qualifiers=qualifiers)
    crs = lexeme.cross_references(request.user)
    cr_groups = []
    for cr in crs:
        if cr_groups and cr.type.desc == cr_groups[-1][0]:
            cr_groups[-1][1].append(cr)
        else:
            cr_groups.append((cr.type.desc, [cr]))
    try:
        pos_name = lexeme.attribute_value(
            LexemeAttribute.objects.get(name=u'dokładniej')).value
    except AttributeError:
        pos_name = lexeme.part_of_speech.full_name
    return {
        'tables': tables,
        'lexeme': lexeme,
        'pattern_list': lexeme.pattern_list(),
        'part_of_speech': pos_name,
        'cross_references': cr_groups,
        'info': lexeme.sgjp_info(),
    }


@render_ajax(template='table_preview.html', method='get')
def table_preview(request, lexeme_id, lip_id, pattern, attr_data=None,
                  gender=None, entry=None, pos=None):
    lexeme = Lexeme.all_objects.get(pk=lexeme_id)
    if not lexeme.perm(request.user, 'view'):
        raise AjaxError('access denied')
    if pos is not None:
        part_of_speech = PartOfSpeech.objects.get(symbol=pos)
    else:
        part_of_speech = lexeme.part_of_speech
    try:
        if entry is not None:
            lexeme.entry = entry
        pattern = Pattern.objects.get(name=pattern)
        gender = Gender.objects.get(id=gender) if gender else None
        if attr_data:
            attr_vals = LexemeAttributeValue.objects.filter(
                id__in=attr_data)
        else:
            attr_vals = None
        if lip_id.startswith('lip_add'):
            lip = LexemeInflectionPattern(lexeme=lexeme, index=0)
        else:
            lip = LexemeInflectionPattern.objects.get(pk=int(lip_id[3:]))
        lip.pattern = pattern
        lip.gender = gender
        lip.root = lip.get_root()
        qualifiers = visible_qualifiers(request.user)
        table = lip.inflection_table(
            '0', separated=True, qualifiers=qualifiers, edit_view=True,
            attr_vals=attr_vals, pos=part_of_speech)
        prepare_table(table)
    except Pattern.DoesNotExist:
        table = None
    return {'table': table, 'color_scheme': part_of_speech.color_scheme}


@ajax(template='odm_forms.html', method='get')
def odm_forms(request, lexeme_id):
    to_return = {}
    l = Lexeme.all_objects.get(pk=lexeme_id)
    if not l.perm(request.user, 'view'):
        raise AjaxError('access denied')
    odm_lexemes = []
    for l in InputLexeme.objects.filter(entry=l.entry):
        odm_lexemes.append(list(l.inputform_set.values_list('form', flat=True)))
    to_return['odm_lexemes'] = odm_lexemes
    return to_return


def attribute_forms(l, part_of_speech=None, genders=None):
    for attr, v in l.attributes_values(part_of_speech, genders):
        if not attr.closed:
            form_class = LexemeOpenAttributeForm
        elif not attr.multiple:
            form_class = LexemeClosedAttributeForm
        else:
            form_class = LexemeMultipleAttributeForm
        if attr.multiple:
            prefix = 'attrmulti%s' % attr.pk
        else:
            prefix = 'attr%s' % attr.pk
        yield form_class(attribute=attr, initial_value=v, prefix=prefix)


@render_ajax(template='extra_attributes.html', method='get')
def extra_attributes(request, lexeme_id, pos, genders=None):
    l = Lexeme.all_objects.get(pk=lexeme_id)
    if not l.perm(request.user, 'view'):
        raise AjaxError('access denied')
    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
    if genders:
        genders = Gender.objects.filter(id__in=genders)
    return {
        'forms': attribute_forms(
            l, part_of_speech=part_of_speech, genders=genders),
    }


@ajax(method='get')
def check_attributes(request, lexeme_id, pos, genders):
    l = Lexeme.all_objects.get(pk=lexeme_id)
    if not l.perm(request.user, 'view'):
        raise AjaxError('access denied')
    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
    if genders:
        genders = Gender.objects.filter(id__in=genders)
    attrs = list(
        l.attributes(part_of_speech, genders).values_list('pk', flat=True))
    return {'attrs': attrs}


@render_ajax(template='lexeme_edit_form.html', method='get')
def lexeme_edit_form(request, id):
    to_return = {}
    l = Lexeme.all_objects.get(pk=id)  # bo może być świeżo utworzony
    if not l.perm(request.user, 'view'):
        raise AjaxError('access denied')
    editable = l.perm(request.user, 'change')
    to_return['editable'] = editable
    owner = l.owner_vocabulary

    to_return['attribute_forms'] = attribute_forms(l)

    editable_vocabs = editable_vocabularies(request.user)
    ro_owner = owner not in editable_vocabs
    to_return['multiple_editable'] = editable and editable_vocabs.count() > 1
    if ro_owner:
        # nie pokazujemy wszystkich, tylko te z właściciela
        ro_qualifiers = l.qualifiers.filter(vocabulary=owner)
    else:
        ro_qualifiers = []
    to_return['owner'] = owner
    ro_vocabularies = l.visible_vocabularies(request.user).exclude(
        pk=owner.pk).exclude(pk__in=editable_vocabs)
    to_return['ro_vocabularies'] = ro_vocabularies
    to_return['ro_qualifiers'] = ro_qualifiers

    to_return['form'] = LexemeEditForm(
        instance=l, editable=editable, user=request.user)
    to_return['id'] = l.pk
    to_return['part_of_speech'] = l.part_of_speech.symbol
    to_return['classification_forms'] = make_classification_forms(
        l, editable=editable)

    lips = l.lexemeinflectionpattern_set.all()
    to_return['lip_forms'] = [
        (LIPEditForm(
            part_of_speech=l.part_of_speech, instance=lip,
            prefix='lip' + str(lip.pk), user=request.user, editable=editable),
         lip.qualifiers.filter(vocabulary=owner) if ro_owner else [])
        for lip in lips]
    to_return['cross_references'] = l.cross_references(request.user)
    if l.homonym_count(request.user) > 0:
        to_return['homonym'] = l.homonym_number
    return to_return


@ajax(method='get')
def check_classifications(request, owner_id, pos):
    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
    owner = Vocabulary.objects.get(pk=owner_id)
    classifications = owner.classifications.filter(
        parts_of_speech=part_of_speech)
    return {
        'classifications': list(classifications.values_list('pk', flat=True))}


def make_classification_forms(lexeme, vocabulary=None, part_of_speech=None,
                              editable=True):
    if not vocabulary:
        vocabulary = lexeme.owner_vocabulary
    if not part_of_speech:
        part_of_speech = lexeme.part_of_speech
    classifications = vocabulary.classifications.filter(
        parts_of_speech=part_of_speech)
    forms = []
    for c in classifications:
        values = lexeme.classification_values(c)
        forms.append(
            ClassificationForm(
                classification=c, values=values, prefix='cl' + str(c.pk),
                editable=editable))
    return forms


@render_ajax(template='classification_forms.html', method='get')
def classification_forms(request, lexeme_id, vocab_id, pos):
    l = Lexeme.all_objects.get(pk=lexeme_id)
    if not l.perm(request.user, 'view'):
        raise AjaxError('access denied')
    part_of_speech = PartOfSpeech.objects.get(symbol=pos)
    if vocab_id:
        vocab = Vocabulary.objects.get(pk=vocab_id)
    else:
        vocab = None
    forms = make_classification_forms(l, vocab, part_of_speech)
    return {'classification_forms': forms}


@render_ajax(template='lexeme_edit_form_row.html', method='get')
def new_lip_edit_row(request, lexeme_id, pos_id, num):
    l = Lexeme.all_objects.get(pk=lexeme_id)
    if not l.perm(request.user, 'change'):
        raise AjaxError('access denied')
    if not pos_id:
        raise AjaxError(_(u'Unspecified part of speech.'))
    pos = PartOfSpeech.objects.get(pk=pos_id)
    lip_form = LIPEditForm(
        part_of_speech=pos, prefix='lip_add_%s' % num, user=request.user)
    return {'lip_form': lip_form, 'editable': True}


@render_ajax(template='cross_reference_row.html', method='get')
def new_cross_reference_row(request, id, pos_id, num):
    l = Lexeme.all_objects.get(pk=id)
    if not l.perm(request.user, 'change'):
        raise AjaxError('access denied')
    prefix = 'cr_add_%s' % num
    pos = PartOfSpeech.objects.get(pk=pos_id)
    cr_form = CrossReferenceForm(lexeme=l, pos=pos, prefix=prefix)
    return {'cr_form': cr_form, 'editable': True}


def insert_new_lexeme(lexeme, request):
    filter = request.session.get('filter')
    sort_rules = request.session.get('sort_rules')
    if filter is None or sort_rules is None:
        return
    query = LexemeQuery({
        'filter': filter,
        'sort_rules': sort_rules,
        'visible_vocabs': list(
            visible_vocabularies(request.user).values_list('id', flat=True)),
        'reader': False,
    })
    id_list = query.get_cached_lexemes()
    if id_list is not None:
        index = bisect_left(id_list, lexeme.entry, cmp=query.lexeme_cmp())
        id_list.insert(index, lexeme.id)
        key = query.cache_key()
        cache.set(key, id_list)


@ajax(method='post')
def update_lexeme(request, form_data):
    form_dict = dict((x['name'], x['value']) for x in form_data)
    l = Lexeme.all_objects.get(pk=form_dict['id'])
    if not l.perm(request.user, 'view'):
        raise AjaxError('access denied')
    owner = l.owner_vocabulary
    new_lexeme = l.entry == ''
    if not l.perm(request.user, 'change'):
        return update_lexeme_qualifiers(
            l, request.user, form_dict, form_data)
    form = LexemeEditForm(data=form_dict, instance=l, user=request.user)
    if form.is_valid():
        l = form.save()
        l.responsible = request.user
        l.deleted = False
        l.fix_homonym_number()
        l.save()
    else:
        raise AjaxError(error_messages(form))
    cand = not l.is_public()

    for vocab in editable_vocabularies(request.user):
        if vocab != owner:
            vocab.set_lexeme(l, vocab in form.cleaned_data['vocabularies'])
    new_owner = form.cleaned_data.get('new_owner')
    if new_owner and new_owner != owner:
        l.change_owner(new_owner)
        l.save()
    for field_name in ('style_qualifiers', 'scope_qualifiers'):
        for qualifier in form.fields[field_name].queryset:
            qualifier.set_for(l, qualifier in form.cleaned_data[field_name])

    classifications = l.owner_vocabulary.classifications.filter(
        parts_of_speech=l.part_of_speech)
    for c in classifications:
        classification_form = ClassificationForm(
            data=form_dict, classification=c, prefix='cl' + str(c.pk),
            required=not cand)
        if classification_form.is_valid():
            values = classification_form.cleaned_data['values']
            if values is None:
                values = ()
            cvs = ClassificationValue.objects.filter(pk__in=values)
            l_cvs = l.classification_values(c)
            for cv in l_cvs:
                if cv.pk not in values:
                    cv.remove_lexeme(l)
            for cv in cvs:
                if cv not in l_cvs:
                    cv.add_lexeme(l)
        else:
            raise AjaxError(error_messages(classification_form))
    for cv in l.classificationvalue_set.all():
        if cv.classification not in classifications:
            cv.remove_lexeme(l)

    for prefix in form_dict['deleted']:
        pk = int(prefix[3:])
        LexemeInflectionPattern.objects.get(pk=pk).delete()
    proposed_crs = {'delete': [], 'create': []}
    for cr_pk in form_dict['deleted_cr']:
        cr = CrossReference.objects.get(pk=cr_pk)
        for rev_cr in cr.reversed():
            if cr.from_lexeme.editable_vocabularies(request.user):
                proposed_crs['delete'].append({
                    'cr_id': rev_cr.id,
                    'entry': rev_cr.from_lexeme.entry,
                    'type_desc': rev_cr.type.desc,
                    'no_other_refs': rev_cr.from_lexeme.refs_to.count() == 1,
                })
        cr.delete()
    submitted_lips = []
    submitted_crs = []
    for pair in form_data:
        name = pair['name']
        prefix = name.split('-')[0]
        if name.startswith('lip') and prefix not in submitted_lips:
            submitted_lips.append(prefix)
            if prefix.startswith('lip_add'):
                lip = LexemeInflectionPattern()
                lip.lexeme = l
            else:
                pk = int(prefix[3:])
                lip = LexemeInflectionPattern.objects.get(pk=pk)
            form_dict[prefix + '-qualifiers'] = get_list(
                form_data, prefix + '-qualifiers')
            lip_form = LIPEditForm(
                part_of_speech=l.part_of_speech, data=form_dict, prefix=prefix,
                instance=lip, user=request.user, index=len(submitted_lips))
            if lip_form.is_valid():
                lip = lip_form.save()
                lip.root = l.get_root(lip.pattern, lip.gender)
                if lip.root is None:
                    raise AjaxError(
                        _(u'Basic form ending doesn\'t match the pattern'))
                for qualifier in lip_form.fields['qualifiers'].queryset:
                    qualifier.set_for(
                        lip, qualifier in lip_form.cleaned_data['qualifiers'])
                lip.save()
            else:
                raise AjaxError(error_messages(lip_form))
        if name.startswith('cr_add') and prefix not in submitted_crs:
            submitted_crs.append(prefix)
            cr_form = CrossReferenceForm(data=form_dict, prefix=prefix)
            if cr_form.is_valid():
                cr = cr_form.save()
                if cr.to_lexeme.editable_vocabularies(request.user):
                    if not cr.reversed():
                        rev_type = cr.type.reversed()
                        if rev_type:
                            proposed_crs['create'].append({
                                'type_id': rev_type.id,
                                'from_lexeme': cr.to_lexeme.id,
                                'to_lexeme': cr.from_lexeme.id,
                                'entry': cr.to_lexeme.entry,
                                'type_desc': rev_type.desc,
                            })
            else:
                raise AjaxError(error_messages(cr_form))
    if len(submitted_lips) == 0 and l.is_public():
        raise AjaxError(
            _(u'Enter inflection or set “candidate” or “litter” status.'))

    extra_attrs = l.attributes()
    for attr in extra_attrs:
        attr_values = attr.values.filter(lexemes=l)
        if not attr.multiple:
            prefix = 'attr' + str(attr.pk)
            assert len(attr_values) <= 1
            if not attr.closed:
                attr_form = LexemeOpenAttributeForm(
                    attribute=attr, data=form_dict, prefix=prefix)
            else:
                attr_form = LexemeClosedAttributeForm(
                    attribute=attr, data=form_dict, prefix=prefix,
                    required=not cand)
            if attr_form.is_valid():
                if not attr.closed:
                    value = attr_form.cleaned_data['value']
                    av, created = LexemeAttributeValue.objects.get_or_create(
                        attribute=attr, value=value)
                else:
                    av = attr_form.cleaned_data['value']
                if not attr_values or attr_values.get() != av:
                    for av1 in attr_values:
                        av1.remove_lexeme(l)
                    if av:
                        av.add_lexeme(l)
            else:
                raise AjaxError(error_messages(attr_form))
        else:
            prefix = 'attrmulti' + str(attr.pk)
            attr_form = LexemeMultipleAttributeForm(
                attribute=attr, data=form_dict, prefix=prefix,
                required=not cand)
            if attr_form.is_valid():
                new_values = attr_form.cleaned_data['value']
                if new_values is None:
                    new_values = ()
                for av in set(attr_values) - set(new_values):
                    av.remove_lexeme(l)
                for av in set(new_values) - set(attr_values):
                    av.add_lexeme(l)
            else:
                raise AjaxError(error_messages(attr_form))
    for av in l.lexemeattributevalue_set.all():
        if av.attribute not in extra_attrs:
            av.remove_lexeme(l)

    l.refresh_data()
    if new_lexeme:
        insert_new_lexeme(l, request)
    computed_derivatives = lexeme_derivatives(l)
    crs = l.refs_to.values_list('to_lexeme__entry', 'type__symbol')
    cr_set = set(tuple(cr) for cr in crs)
    needed_derivatives = [
        d for d in computed_derivatives
        if (d['entry'], d['cr_type']) not in cr_set]
    return {'derivatives': needed_derivatives, 'proposed_crs': proposed_crs}


@ajax(method='post')
def create_derivatives(request, lexeme_id, chosen_derivatives):
    lexeme = Lexeme.objects.get(id=lexeme_id)
    if not lexeme.perm(request.user, 'change'):
        raise AjaxError('access denied')
    new_derivatives = {}
    for der_data in chosen_derivatives:
        pos = der_data['pos']
        cr_type = der_data['cr_type']
        entry = der_data['entry']
        if entry == '':
            raise AjaxError(_(u'Empty entry'))
        exists = CrossReference.objects.filter(
            from_lexeme=lexeme, to_lexeme__entry=entry,
            type__symbol=cr_type, type__to_pos=pos)
        if not exists:
            new_lexemes = create_derivative(
                lexeme, pos, cr_type, entry, pl=der_data.get('pl'),
                index=der_data['index'])
            for der in new_lexemes:
                insert_new_lexeme(der, request)
            new_derivatives[cr_type] = new_lexemes
    if lexeme.part_of_speech_id == 'adj':
        if 'adjadv' in new_derivatives and 'adjadvc' in new_derivatives:
            adv = new_derivatives['adjadv'][0]
            advcom = new_derivatives['adjadvc'][0]
            adv.add_cross_reference(advcom, 'advcom')
            advcom.add_cross_reference(adv, 'comadv')
    return {}


def cr_tuple(cr):
    pos = cr.to_lexeme.part_of_speech.symbol
    if pos in ('ppas', 'appas'):
        lip = cr.to_lexeme.lexemeinflectionpattern_set.get()
        ending9 = Ending.objects.get(
            pattern=lip.pattern, base_form_label__symbol='9')
        plnommo = lip.root + ending9.string
        return cr.type.symbol, cr.to_lexeme.entry, plnommo, pos
    else:
        return cr.type.symbol, cr.to_lexeme.entry, pos


def der_tuple(der):
    if der['pos'] in ('ppas', 'appas'):
        return der['cr_type'], der['entry'], der['pl'], der['pos']
    else:
        return der['cr_type'], der['entry'], der['pos']


def refresh_derivatives(lexeme, request=None):
    existing_ders = lexeme.refs_to.filter(
        type__symbol__in=('verpact', 'verppas', 'verappas', 'verger'))
    existing_der_set = set(cr_tuple(cr) for cr in existing_ders)
    computed_ders = list(lexeme_derivatives(lexeme))
    computed_der_set = set(der_tuple(der) for der in computed_ders)
    if computed_der_set != existing_der_set:
        for der_data in computed_ders:
            cr_type = der_data['cr_type']
            entry = der_data['entry']
            pos = der_data['pos']
            if der_tuple(der_data) not in existing_der_set:
                new_lexemes = create_derivative(
                    lexeme, pos, cr_type, entry, pl=der_data.get('pl'),
                    index=der_data['index'])
                if request:
                    for der in new_lexemes:
                        insert_new_lexeme(der, request)
        for cr in existing_ders:
            if cr_tuple(cr) not in computed_der_set:
                cr.reversed().delete()
                cr.delete()


@ajax(method='post')
def update_back_references(request, deleted_cr, created_cr):
    user = request.user
    for cr_data in deleted_cr:
        cr = CrossReference.objects.get(id=int(cr_data['cr_id']))
        if cr.from_lexeme.perm(user, 'change'):
            cr.delete()
        else:
            raise AjaxError('access denied')
    for cr_data in created_cr:
        from_lexeme = Lexeme.objects.get(id=int(cr_data['from_lexeme']))
        to_lexeme = Lexeme.objects.get(id=int(cr_data['to_lexeme']))
        cr_type = CrossReferenceType.objects.get(id=cr_data['type_id'])
        if from_lexeme.perm(user, 'change'):
            CrossReference.objects.create(
                from_lexeme=from_lexeme, to_lexeme=to_lexeme, type=cr_type)
        else:
            raise AjaxError('access denied')
    return {}


def update_lexeme_qualifiers(lexeme, user, form_dict, form_data):
    owner = lexeme.owner_vocabulary
    editable_vocabs = editable_vocabularies(user).exclude(pk=owner.pk)
    # l_editable_vocabs = lexeme.editable_vocabularies(user)
    l_editable_vocabs = editable_vocabularies(user)
    qualifiers = Qualifier.objects.filter(vocabulary__in=l_editable_vocabs)
    for qualifier in qualifiers:
        qualifier.set_for(
            lexeme, unicode(qualifier.pk) in form_dict.get('qualifiers', ()))
    for vocab in editable_vocabs:
        vocab.set_lexeme(lexeme, vocab.pk in form_dict['vocabularies'])
    submitted_lips = []
    for pair in form_data:
        name = pair['name']
        prefix = name.split('-')[0]
        if name.startswith('lip') and prefix not in submitted_lips:
            submitted_lips.append(prefix)
            pk = int(prefix[3:])
            lip = LexemeInflectionPattern.objects.get(pk=pk)
            lip_qualifiers = get_list(form_data, prefix + '-qualifiers')
            for qualifier in qualifiers:
                qualifier.set_for(lip, unicode(qualifier.pk) in lip_qualifiers)
    return {}


def get_list(form_data, name):
    return [pair['value'] for pair in form_data if pair['name'] == name]


@ajax(method='post')
def delete_lexeme(request, lexeme_id):
    lexeme_id = int(lexeme_id)
    l = Lexeme.all_objects.get(pk=lexeme_id)
    if not l.perm(request.user, 'change'):
        raise AjaxError('access denied')
    if not l.deleted:
        l.deleted = True
        l.save()
        key_list = cache.get('key_list', [])
        for key in key_list:
            pk_list = cache.get(key)
            if pk_list and lexeme_id in pk_list:
                pk_list.remove(lexeme_id)
                cache.set(key, pk_list)
        for lexeme_list in LexemeList.objects.all():
            lexeme_list.remove_lexeme(l)
    return {}


@ajax(method='get')
def check_pos(request, pos_id, had_gender):
    if (pos_id in ('subst', 'skrs', 'osc')) == had_gender:
        return {'answer': 'yes'}
    else:
        return {'answer': 'no'}


@ajax(method='get')
def check_pattern(request, pattern_name, gender_id):
    lips = LexemeInflectionPattern.objects.filter(
        gender_id=gender_id, pattern__name=pattern_name)
    lips = lips.exclude(lexeme__status__in=Lexeme.HIDDEN_STATUSES)
    if lips.exists():
        return {'answer': 'yes'}
    else:
        return {'answer': 'no'}


START_ID = 1000000


@ajax(method='post')
def create_lexeme(request):
    owner = request.user.usersettings.get_default_owner()
    pos_id = request.user.usersettings.default_pos_id or 'subst'
    if not owner:
        raise AjaxError(_(u'Empty owner dictionary'))
    next_id = Lexeme.all_objects.filter(
        pk__gte=START_ID).aggregate(Max('id'))['id__max']
    next_id = next_id + 1 if next_id else START_ID
    l = Lexeme.objects.create(
        id=next_id, part_of_speech_id=pos_id,
        owner_vocabulary=owner, status=Lexeme.STATUS_CANDIDATE,
        responsible=request.user, deleted=True)
    owner.add_lexeme(l)
    return {'id': l.id}


@ajax(method='post')
def clone_lexeme(request, lexeme_id):
    try:
        lexeme = Lexeme.objects.get(id=lexeme_id)
    except Lexeme.DoesNotExist:
        raise AjaxError(_(u'Cannot clone a lexeme before it is created.'))
    owner = request.user.usersettings.get_default_owner()
    if not owner:
        raise AjaxError(_(u'Empty owner dictionary'))
    next_id = Lexeme.all_objects.filter(
        pk__gte=START_ID).aggregate(Max('id'))['id__max']
    next_id = next_id + 1 if next_id else START_ID
    comment = u'Leksem sklonowany %s' % (format_date(datetime.datetime.now()))
    new_lexeme = Lexeme.objects.create(
        id=next_id, part_of_speech_id=lexeme.part_of_speech_id,
        entry=lexeme.entry, pronunciation=lexeme.pronunciation,
        valence=lexeme.valence, source=lexeme.source,
        borrowing_source_id=lexeme.borrowing_source_id, note=lexeme.note,
        extended_note=lexeme.extended_note, specialist=lexeme.specialist,
        status=lexeme.status, comment=comment,
        owner_vocabulary_id=owner, responsible=request.user)
    owner.add_lexeme(new_lexeme)
    new_lexeme.fix_homonym_number()  # nie zadziałał :/
    new_lexeme.save()
    new_lexeme.qualifiers = lexeme.qualifiers.all()
    for lip in lexeme.lexemeinflectionpattern_set.all():
        new_lip = LexemeInflectionPattern.objects.create(
            lexeme=new_lexeme, index=lip.index, pattern=lip.pattern,
            gender=lip.gender, root=lip.root)
        new_lip.qualifiers = lip.qualifiers.all()
    for lav in lexeme.lexemeav_set.all():
        LexemeAV.objects.create(
            lexeme=new_lexeme, attribute_value=lav.attribute_value)
    for lcv in lexeme.lexemecv_set.all():
        LexemeCV.objects.create(
            lexeme=new_lexeme, classification_value=lcv.classification_value)
    new_lexeme.refresh_data()
    insert_new_lexeme(new_lexeme, request)
    return {'new_id': new_lexeme.id}


@ajax(method='get')
def homonym_count(request, entry, lexeme_id):
    lexeme = Lexeme.all_objects.get(id=lexeme_id)
    if not lexeme.perm(request.user, 'view'):
        raise AjaxError('access denied')
    lexeme.entry = entry
    return {'count': lexeme.homonym_count(request.user)}


@ajax(method='get')
def cr_homonyms(request, entry, cr_type):
    cr_type = CrossReferenceType.objects.get(pk=cr_type)
    pos = cr_type.to_pos
    lexemes = filter_visible(Lexeme.objects.distinct(), request.user).filter(
        entry=entry, part_of_speech=pos)
    aspect = LexemeAttribute.objects.get(name=u'aspekt')
    if pos in aspect.parts_of_speech.all():
        middle_labels = (_(u'Aspect'),)

        def middle_fields(lexeme, lip_data):
            aspect_value = lexeme.attribute_value(aspect)
            return aspect_value.value if aspect_value else '',
    elif pos.lexical_class_id == 'subst':
        middle_labels = (_(u'Gender'),)

        def middle_fields(lexeme, lip_data):
            return lip_data['genders'],
    else:
        middle_labels = ()

        def middle_fields(lexeme, lip_data):
            return ()
    labels = (
        (_(u'Hom. №'),) + middle_labels +
        (_(u'Pattern'), _(u'Dictionaries'), _(u'Status')))

    def make_row(lexeme, lip_data):
        status = force_unicode(dict(Lexeme.STATUS_CHOICES)[lexeme.status])
        vocabs = '/'.join(lexeme.vocab_list())
        return (
            (lexeme.homonym_number,) + middle_fields(lexeme, lip_data) +
            (lip_data['patterns'], vocabs, status))

    lexemes_data = [
        make_row(l, l.lip_data()) for l in lexemes.order_by('homonym_number')
    ]
    return {'labels': labels, 'lexemes': lexemes_data}


@ajax(template='new_action_row.html', method='get')
def new_action_row(request, num):
    form = ActionFieldForm(prefix='action_%s' % num)
    return {'form': form}


@ajax(method='get')
def dynamic_action_fields(request, field_name):
    action_form, value_form = dict(ACTION_FIELDS)[field_name][1:3]
    return {
        'action': action_form()['action'].as_widget(),
        'value': value_form(request)['value'].as_widget(),
    }


@ajax(method='post', permission_required='dictionary.change_lexeme')
def execute_group_actions(request, actions, filter):
    query = LexemeQuery({
        'filter': filter,
        'sort_rules': [],
        'visible_vocabs': list(
            visible_vocabularies(request.user).values_list('id', flat=True)),
        'reader': False
    })
    pk_list = query.get_id_list()
    lexemes = Lexeme.objects.filter(pk__in=pk_list)
    for l in lexemes:
        for action in actions:
            field = action['field']
            if field == 'status':
                # action['type'] == 'set'
                l.status = action['value']
            elif field == 'using_vocabulary':
                vocab = Vocabulary.objects.get(pk=action['value'])
                if action['type'] == 'add':
                    vocab.add_lexeme(l)
                else:   # 'remove'
                    if vocab != l.owner_vocabulary:
                        vocab.remove_lexeme(l)
            else:  # field == 'lexeme_qualifier'
                qual = Qualifier.objects.get(pk=action['value'])
                # a co jeśli koliduje z innym?
                if action['type'] == 'add':
                    l.qualifiers.add(qual)  # add
                else:
                    l.qualifiers.remove(qual)  # add
        l.save()
    return {}


@ajax(method='get', login_required=False)
def get_entry(request, lexeme_id):
    lexeme = get_object_or_404(Lexeme, id=lexeme_id)
    return {'entry': lexeme.entry}