#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = 'helljump'

from PyQt4 import QtGui
import logging
import startup
import re
from formlayout import fedit
import transaction
from utils import MyProgressDialog


# TODO: починить кривую нарезку


log = logging.getLogger(__name__)


hr_re = re.compile("<hr class=['\"]?more['\"]?>", re.I)
hr = "<hr class='more'>"
more = "<!--more-->"
p_re = re.compile("</?[^>]+>|</p>", re.I)
br_re = re.compile("</?[^>]+>|<br/?>", re.I)
word_re = re.compile("</?[^>]+>|[\s\.,!?]", re.I)
tags_re = re.compile('</?[^>]+>', re.U | re.S | re.M)


def process(prj, parent=None):
    prefs = prj.root().get('prefs/splitter', [
        True, 3, 5, 30, 255, True, True, True, u'...'
    ])
    data = [
        (u'Учитывать <b>&lt;!--more--&gt;</b>', prefs[0]),
        (u'Количество абзацев <b>&lt;P&gt;</b>', prefs[1]),
        (u'Количество <b>&lt;BR&gt;</b>', prefs[2]),
        (u'Количество слов', prefs[3]),
        (u'Количество символов', prefs[4]),
        (None, None),
        (u'Очищать теги', prefs[5]),
        (u'Копировать текст', prefs[6]),
        (u'Переразбивать заново', prefs[7]),
        (u'Добавлять после вступления', prefs[8]),
    ]
    rc = fedit(data, title=u'Вставка "Подробнее"', comment=u'Разделитель вставляется после первого совпавшего условия.',
        parent=parent, icon=QtGui.QIcon(':/aaaa32.png'))
    if rc is None:
        return
    prj.root()['prefs/splitter'] = rc
    transaction.commit()
    more_to_hr, para, br, words, chars, clear_tags, copy_text, remove_hr, append_s = rc
    para -= 1
    words -= 1
    br -= 1
    chars -= 1
    docs = prj.root()['documents']
    pdlg = MyProgressDialog(u'Генератор меток', u'Обработка', u'Отмена', 0, len(docs), parent=parent)
    pdlg.show()
    try:
        for i, doc in enumerate(docs):
            if hr_re.search(doc.text) and not remove_hr:
                continue
            doc.text = hr_re.sub('', doc.text)
            if doc.text.find(more) > -1 and more_to_hr:
                if __name__ == '__main__':
                    pass
                else:
                    doc.text = doc.text.replace(more, hr)
                continue
            egg = list(p_re.finditer(doc.text))
            if len(egg) > para:
                last = egg[para].span()[1]
            else:
                last = len(doc.text)
            egg = list(word_re.finditer(doc.text))
            if len(egg) > words:
                last = min(last, egg[words].span()[0])
            egg = list(br_re.finditer(doc.text))
            if len(egg) > br:
                last = min(last, egg[br].span()[1])
            last = min(chars, last)
            if last < 0:
                continue
            log.debug('last %i', last)
            intro = doc.text[:last]
            full = doc.text[last:]
            if clear_tags:
                intro = tags_re.sub('', intro)
            intro = "%s%s" % (intro, append_s)
            if copy_text:
                if __name__ == '__main__':
                    print u"%s\n%s\n%s" % (intro, hr, doc.text)
                else:
                    doc.text = "%s\n%s\n%s" % (intro, hr, doc.text)
            else:
                if __name__ == '__main__':
                    print u"%s\n%s\n%s" % (intro, hr, full)
                else:
                    doc.text = "%s\n%s\n%s" % (intro, hr, full)
            pdlg.set_value(i)
            QtGui.qApp.processEvents()
            if pdlg.wasCanceled():
                transaction.abort()
                break
            if __name__ == '__main__':
                break
        else:
            transaction.commit()
            if parent is not None:
                parent.statusBar().showMessage(u'Нарезали', 3000)
    except:
        transaction.abort()
        raise
    finally:
        pdlg.close()


if __name__ == '__main__':

    """
    text = u'''<p>dw copnibe fv</P><p>po u<br/>fn dv</p><p>we dfw<br>se df v</p>'''
    p = 2
    egg = list(word_re.finditer(text))
    if len(egg) > p:
        last = egg[p].span()[0]
    else:
        last = len(text)
    print last
    sys.exit()
    """

    logging.basicConfig(level=logging.DEBUG)
    root = startup.CONN.root()
    prj = root["projects"][0]
    prj.open()
    process(prj)
    prj.close()
