# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.management import BaseCommand
from multiprocessing import Process

from talos.models.diary import Diary
from talos.models.topic import Problem
from talos.logger import info_logger

user_ids = [33689650]
BATCH_SIZE = 500


def offline_topic():
    topic_ids = list(Problem.objects.using(settings.SLAVE_DB_NAME).filter(
        user_id__in=user_ids
    ).values_list('id', flat=True))

    while topic_ids:
        Problem.objects.filter(id__in=topic_ids[: BATCH_SIZE]).update(is_online=False)
        info_logger.info('offline topic ids {}'.format(topic_ids[: BATCH_SIZE]))
        print('offline topic ids: ', topic_ids[: BATCH_SIZE])
        topic_ids = topic_ids[500:]


def offline_diary():
    diary_ids = list(Diary.objects.using(settings.SLAVE_DB_NAME).filter(
        user_id__in=user_ids
    ).values_list('id', flat=True))

    while diary_ids:
        Diary.objects.filter(id__in=diary_ids[: BATCH_SIZE]).update(is_online=False)
        info_logger.info('offline diary ids {}'.format(diary_ids[: BATCH_SIZE]))
        print('offline diary ids: ', diary_ids[: BATCH_SIZE])
        diary_ids = diary_ids[500:]


class Command(BaseCommand):
    """
    python django_manage.py diary_topic_offline
    """

    def handle(self, *args, **kwargs):
        print('start')
        p_list = []
        d = Process(target=offline_diary, args=())
        t = Process(target=offline_topic, args=())
        p_list.extend([d, t])
        for i in p_list:
            i.start()

        for j in p_list:
            j.join()
        print('end')
