# -*- coding: UTF-8 -*-
from re import sub, VERBOSE

from anki.template.furigana import kanji
from aqt import mw

from util import getFilters, getSrcDstMappingForFilters


def containsKanji(text):
    """
    Checks whether text contains kanji.

    Adapted from https://github.com/larsyencken/cjktools/blob/master/cjktools/scripts.py

    @param text: The string to check for kanji.
    @type text: Unicode
    """
    return any(True if u'\u4e00' <= c <= u'\u9fa5' else False for c in text)


def killFurigana(text):
    """
    Removes Anki-formatted Furigana (i.e. in brackets, []) from text. Also
    removes spaces that had to be inserted for correct furigana placement.

    @param text: Text from which to remove bracketed furigana
    @type text: Unicode
    """
    return sub(r'''(^|\ )       # Beginning, or a space
                   ([^ []+)     # Word itself (no space or bracket)
                   \[ [^\]]+ \] # Brackets and their contents''',
               r'\2', text, flags=VERBOSE)


def worker(note, srcField, dstField, hasKanjiField):
    if srcField not in note or dstField not in note:
        return False
    srcTxt = unicode(mw.col.media.strip(note[srcField]))

    if containsKanji(srcTxt):
        note[dstField] = kanji(srcTxt)
        if hasKanjiField in note:
            note[hasKanjiField] = u'1'
    else:
        note[dstField] = srcTxt
        if hasKanjiField in note:
            note[hasKanjiField] = u''
    return True


def addFurikilled(note, flag=False, currentFieldIndex=None):
    fs = getFilters(note)
    if fs is None:
        return flag
    srcDstFieldMapping = getSrcDstMappingForFilters(fs)

    model = note.model()

    if currentFieldIndex != None: # We've left a field
        srcField = model['flds'][currentFieldIndex]['name']
        # But it isn't a source field
        if srcField not in srcDstFieldMapping:
            return flag
    dstField = srcDstFieldMapping[srcField][0]
    hasKanjiField = srcDstFieldMapping[srcField][1]

    flush = worker(note, srcField, dstField, hasKanjiField)
    if flush:
        note.flush()
    return flush
