# -*- coding: UTF-8 -*-

from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataSQLQuery

from api.models import WordRel
from hera.utils import model_edit, commastr_to_list


def wordrel_edit(object_id=None, data=None):
    synonym_list = data.pop('synonym_list', None)
    resemble_list = data.pop('resemble_list', None)
    obj = model_edit(WordRel, object_id, data)
    if synonym_list is not None:
        synonym_list.append(obj.keyword)
        obj.save_synonym_words(synonym_list)
    if resemble_list is not None:
        obj.save_resemble_words(resemble_list)
    return obj


@DB
class WordRelDQ(DataSQLQuery):
    model = WordRel

    def filter_keyword(self, srch_key, srch_val, regex=False):
        if srch_val:
            self.distinct = True
        return self._default_q('all_synonyms__word', srch_val, regex)

    def create(self, **kwargs):
        keyword = kwargs['keyword']
        WordRel.check_constraint([keyword])
        synonym_str = kwargs.pop('synonyms_string', None)
        kwargs['synonym_list'] = None
        if synonym_str is not None:
            synonym_list = commastr_to_list(synonym_str)
            WordRel.check_constraint(synonym_list)
            synonym_list.append(keyword)
            kwargs['synonym_list'] = synonym_list

        resemble_str = kwargs.pop('resembles_string', None)
        kwargs['resemble_list'] = None
        if resemble_str is not None:
            resemble_list = commastr_to_list(resemble_str)
            kwargs['resemble_list'] = resemble_list

        word_rel = wordrel_edit(None, kwargs)
        return {'id': word_rel.id}

    def update(self, updates, **kwargs):
        id_ = kwargs.get('id', '')
        act_delete = updates.pop('act_delete', False)
        if act_delete:
            # 删除操作
            WordRel.objects.filter(id=id_).delete()
            return {'id': id_}
        else:
            synonym_str = updates.pop('synonyms_string', None)
            updates['synonym_list'] = None
            if synonym_str is not None:
                synonym_list = commastr_to_list(synonym_str)
                WordRel.check_constraint(synonym_list, id_)
                updates['synonym_list'] = synonym_list

            resemble_str = updates.pop('resembles_string', None)
            updates['resemble_list'] = None
            if resemble_str is not None:
                resemble_list = commastr_to_list(resemble_str)
                updates['resemble_list'] = resemble_list

            word_rel = wordrel_edit(id_, updates)
            return {'id': word_rel.id}
