# -*- coding: utf-8 -*-
import logging

from django.utils import timezone

from idm.core.management.base import IdmBaseCommand
from idm.core.models import CommandTimestamp
from idm.core.models.metrikacounter import MetrikaCounter

log = logging.getLogger(__name__)


class Command(IdmBaseCommand):
    help = 'Данная manage.py команда синхронизирует таблицу MetrikaCounter c YT'

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)
        parser.add_argument('--full', dest='full', action='store_true', default=False)
        parser.add_argument('--since', dest='since', action='store', type='datetime')

    def idm_handle(self, *args, **options):
        if options['full']:
            MetrikaCounter.sync_from_yt(options['full'])

        elif since := options.get('since'):
            MetrikaCounter.sync_from_yt(time_offset=int((timezone.now() - since).total_seconds()))
        elif last_run := CommandTimestamp.objects.filter(
                command=self.command_name, last_success_finish__isnull=False
        ).first():  # type: CommandTimestamp
            MetrikaCounter.sync_from_yt(time_offset=int((timezone.now() - last_run.last_success_start).total_seconds()))
        else:
            MetrikaCounter.sync_from_yt(full=True)
