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

from api.models import PushUser, PushTask2


class Command(BaseCommand):
    """
    pushuser 表历史数据删除 删除一个月之前的 push task 数据
    python manage.py del_pushuser_old_data
    """

    def handle(self, *args, **options):
        today = datetime.datetime.today()
        last_day = today - datetime.timedelta(days=30)
        push_task = PushTask2.objects.using(settings.SLAVE_DB_NAME).filter(
            created_time__lte=last_day
        ).last()
        push_task_id = push_task and push_task.id or 0
        if not push_task_id:
            print('There is no data to delete')
            return

        print('delete pushtask_id less than or equal to {}'.format(push_task_id))
        push_user = PushUser.objects.using(settings.SLAVE_DB_NAME).filter(
            pushtask_id__lte=push_task_id
        ).last()
        max_id = push_user and push_user.id or 0
        if not max_id:
            print('There is no data to delete')
            return
        index = 2000
        while index <= max_id:
            PushUser.objects.filter(id__lte=index).delete()
            index += 2000
            if index > max_id:
                index = max_id
        print('Done')
