# -*- coding: UTF-8 -*-
from django.db import models
from rpc.exceptions import GaiaRPCFaultException


class Word(models.Model):
    class Meta:
        app_label = 'api'
        db_table = 'api_word'

    text = models.CharField(u'词名', max_length=50, unique=True, db_index=True)


class SynonymGroup(models.Model):
    class Meta:
        app_label = 'api'
        db_table = 'api_synonymgroup'

    words = models.ManyToManyField(Word, verbose_name=u'同义词', db_table='api_synonymgroup_word')
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    updated_time = models.DateTimeField(verbose_name=u'最后更新时间', auto_now=True)

    @property
    def words_list(self):
        return [w.text for w in self.words.all()]

    @property
    def words_string(self):
        return u','.join(self.words_list)

    def update_words(self, word_list):
        # 注意unicode与十六进制set操作
        old = set(self.words_list)
        new = set(filter(None, word_list))
        to_add = list(new - old)
        to_del = list(old - new)
        self.add_words(to_add)
        self.del_words(to_del)

    def add_words(self, word_list):
        words = []
        for w in word_list:
            obj, is_create = Word.objects.get_or_create(text=w)
            words.append(obj)
        self.words.add(*words)

    def del_words(self, word_list):
        words = [Word.objects.get(text=t) for t in word_list]
        self.words.remove(*words)

