# coding=utf8

from __future__ import unicode_literals, absolute_import, print_function

from django.db import models

from talos.services.tag import TagService

from .topic import Problem


class ProblemTag(models.Model):
    class Meta:
        app_label = 'talos'
        db_table = 'api_problemtag'

    problem = models.ForeignKey(Problem)
    tag_id = models.IntegerField()

    def __unicode__(self):
        return "%s:%d" % (self.tag_id, self.problem.id)

    @classmethod
    def create_bind(cls, problem_id, tag_id):
        topic_exists = Problem.objects.filter(id=problem_id).exists()
        tag_exists = TagService.get_tag_by_tag_id(id=tag_id) is not None
        if topic_exists and tag_exists:
            pt = cls()
            pt.problem_id = problem_id
            pt.tag_id = tag_id
            pt.save()
            return True
        else:
            return False

    @classmethod
    def get_tag_ids_by_topic_id(cls, problem_id):
        tag_ids = cls.objects.filter(problem_id=problem_id).values_list('tag_id', flat=True)
        return tag_ids


class ProblemTagV3(models.Model):
    class Meta:
        db_table = 'api_problem_tag_v3'
        app_label = "talos"

    problem_id = models.IntegerField(verbose_name="帖子id", db_index=True)
    tag_v3_id = models.IntegerField(verbose_name="标签V3", db_index=True)