import datetime
from time import sleep

import croniter
from django.core.management import BaseCommand
from django.utils import timezone
from requests import get

from stats.models import Snapshot
from web.models import Project


class Command(BaseCommand):
    def handle(self, *args, **options):
        while True:
            for project in Project.objects.filter(next_stats_fetch_time__lte=timezone.now()):
                if project.stats_enabled:
                    if not project.stats_link:
                        continue
                    try:
                        response = get(project.stats_link)
                    except:
                        continue
                    if response.status_code != 200:
                        continue
                    Snapshot.objects.create(project=project, data=response.json())
                if not project.stats_cron:
                    continue
                cron = croniter.croniter(project.stats_cron, timezone.now())
                next_date = cron.get_next(datetime.datetime)
                project.next_stats_fetch_time = next_date
                project.save()
            sleep(5 * 60)
