# coding=utf-8
import datetime
from django.core.management import BaseCommand

from api.models import Problem, TopicReply
from django.contrib.auth.models import User


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('topic_id', type=str)

    def handle(self, *args, **options):
        file = open('person.csv', 'w')
        if options['topic_id'] is None:
            return
        topic_id = options['topic_id']
        topic = Problem.objects.get(id=topic_id)

        # 一级回复
        topic_all_replys = topic.topicreply_set.filter(commented_reply__isnull=True, is_online=True)

        for reply in topic_all_replys:
            # 二级回复
            users = TopicReply.objects.filter(commented_reply=reply).\
                exclude(user=reply.user).values_list('user_id', flat=True).distinct()
            print(users)
            users = list(set(users))
            users = User.objects.filter(id__in=users, date_joined__gte=datetime.datetime(2017, 1, 25),
                                        date_joined__lte=datetime.datetime(2017, 2, 2))
            num = users.count()

            if num > 4:
                device = reply.user.devices.last()
                file.write(str(reply.user_id) + ', ' + str(device.device_id))
                print(str(reply.user_id) + ', ' + str(device.device_id))

        file.close()
