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

__author__ = 'helljump'

from PyQt4 import QtGui
from PyQt4 import QtCore
import logging
import startup
from ui.catter_ui import Ui_Dialog
import transaction
from utils import MyProgressDialog
from tagger import Tagger
import random


log = logging.getLogger(__name__)


class Dialog(QtGui.QDialog, Ui_Dialog):
    def __init__(self, project, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUi(self)
        self.prj = project
        self.parent = parent
        tags = project.root()['cats']
        self.tags_te.setPlainText(', '.join(tags))
        if startup.CFG.contains('catter/geometry'):
            self.restoreGeometry(startup.CFG.value('catter/geometry').toByteArray())

    def closeEvent(self, evt):
        log.debug('close event')
        tags = set([tag.strip() for tag in unicode(self.tags_te.toPlainText()).split(',') if tag.strip()])
        self.prj.root()['cats'] = tags
        transaction.commit()
        startup.CFG.setValue('cats/geometry', self.saveGeometry())
        evt.accept()

    @QtCore.pyqtSlot()
    def on_actionApply_triggered(self):
        log.debug('apply cats')
        docs = self.prj.root()['documents']
        pdlg = MyProgressDialog(u'Генератор категорий', u'Назначение документам категорий', u'Отмена', 0, len(docs), parent=self)
        pdlg.show()
        tagger = Tagger()
        alltags = set([tag.strip() for tag in unicode(self.tags_te.toPlainText()).split(',') if tag.strip()])
        for i, doc in enumerate(docs):
            doctags = tagger.words(doc.title) | tagger.words(doc.text)
            egg = set(doctags & alltags)
            if egg:
                spam = egg.pop().capitalize()
                doc.cats = set([spam])
            else:
                doc.cats = set([u'Новости'])
            pdlg.set_value(i)
            QtGui.qApp.processEvents()
            if pdlg.wasCanceled():
                transaction.abort()
                break
        transaction.commit()
        if self.parent is not None:
            self.parent.model.layoutChanged.emit()
        pdlg.close()

    @QtCore.pyqtSlot()
    def on_actionRandom_triggered(self):
        alltags = [tag.strip() for tag in unicode(self.tags_te.toPlainText()).split(',') if tag.strip()]
        if not alltags:
            QtGui.QMessageBox.critical(self, u'Ошибка', u'Нет категорий для назначения')
            return
        log.debug('apply random cats')
        docs = self.prj.root()['documents']
        pdlg = MyProgressDialog(u'Генератор категорий', u'Назначение документам категорий', u'Отмена', 0, len(docs), parent=self)
        pdlg.show()
        for i, doc in enumerate(docs):
            spam = random.choice(alltags).capitalize()
            doc.cats = set([spam])
            pdlg.set_value(i)
            QtGui.qApp.processEvents()
            if pdlg.wasCanceled():
                transaction.abort()
                break
        transaction.commit()
        if self.parent is not None:
            self.parent.model.layoutChanged.emit()
        pdlg.close()

    @QtCore.pyqtSlot()
    def on_actionCreate_triggered(self):
        rc = QtGui.QMessageBox.question(self, u'Генерация категорий', u'Текущие категории будут очищены. Продолжать?',
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if rc == QtGui.QMessageBox.No:
            return
        docs = self.prj.root()['documents']
        pdlg = MyProgressDialog(u'Генератор категорий', u'Обработка', u'Отмена', 0, len(docs), parent=self)
        pdlg.show()
        tagger = Tagger()
        for i, doc in enumerate(docs):
            tagger.generate(doc.title)
            tagger.generate(doc.text)
            pdlg.set_value(i)
            QtGui.qApp.processEvents()
            if pdlg.wasCanceled():
                break
        self.tags_te.setPlainText(', '.join(tagger.tags(100)))
        pdlg.close()


def process(prj, parent=None):
    dlg = Dialog(prj, parent)
    dlg.exec_()

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