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

import sys
from PyQt4.Qt import Qt, QApplication, QLineEdit, QCompleter, QStringListModel


class TagsCompleter(QCompleter):

    def __init__(self, parent, all_tags):
        QCompleter.__init__(self, parent)
        self.all_tags = set(all_tags)

    def update(self, text_tags, completion_prefix):
        tags = list(self.all_tags.difference(text_tags))
        model = QStringListModel(tags, self)
        self.setModel(model)
        self.setCompletionPrefix(completion_prefix)
        if completion_prefix.strip() != '':
            self.complete()


class CompleterLineEdit(QLineEdit):

    def __init__(self, parent=None, tags=None):
        QLineEdit.__init__(self, parent)
        self.textChanged.connect(self.text_changed)
        if tags is None:
            tags = []
        self.completer = TagsCompleter(self, tags)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.activated.connect(self.complete_text)
        self.completer.setWidget(self)

    def text_changed(self, text):
        all_text = unicode(text)
        text = all_text[:self.cursorPosition()]
        prefix = text.split(',')[-1].strip()
        text_tags = []
        for t in all_text.split(','):
            t1 = unicode(t).strip()
            if t1 != '':
                text_tags.append(t1)
        text_tags = list(set(text_tags))
        self.completer.update(text_tags, prefix)

    def complete_text(self, text):
        cursor_pos = self.cursorPosition()
        before_text = unicode(self.text())[:cursor_pos]
        after_text = unicode(self.text())[cursor_pos:]
        prefix_len = len(before_text.split(',')[-1].strip())
        self.setText('%s%s, %s' % (before_text[:cursor_pos - prefix_len], text,
            after_text))
        self.setCursorPosition(cursor_pos - prefix_len + len(text) + 2)
        self.setModified(True)

    def set_tags(self, tagset):
        self.completer.all_tags = tagset


if __name__ == '__main__':
    app = QApplication(sys.argv)
    tags = set([u'гут', u'бэд', u'хто его знает'])
    editor = CompleterLineEdit(None, tags)
    editor.show()
    app.exec_()
    print editor.isModified()
