import datetime

import croniter
import validators
from django.utils import timezone

from BaseLib.BaseView import BaseView
from stats.models import Snapshot


class StatsView(BaseView):
    endpoint = ''
    view_file = 'stats.html'
    required_login = True

    def get(self):
        count = 12
        snapshots = list(Snapshot.objects.filter(project=self.request.user.selected_project).order_by('-created_at')[:count])
        keys = set()
        for snapshot in snapshots:
            for key in snapshot.data:
                keys.add(key)
        keys = list(keys)
        keys.sort()
        rows = [[key] for key in keys]
        times = []
        for snapshot in snapshots:
            times.append(snapshot.created_at)
            for index, key in enumerate(keys):
                rows[index].append(snapshot.data.get(key))
        self.context['data'] = rows
        self.context['times'] = times
        self.context['err'] = 'err' in self.request.GET

    def post(self):
        self.request.user.selected_project.stats_enabled = 'enabled' in self.request.POST
        if self.request.POST['link'] == "":
            self.request.user.selected_project.stats_link = None
        elif validators.url(self.request.POST['link']):
            self.request.user.selected_project.stats_link = self.request.POST['link']
        else:
            return '/stats?err=true'
        if self.request.POST['cron'] == "":
            self.request.user.selected_project.stats_cron = None
        elif croniter.croniter.is_valid(self.request.POST['cron']):
            self.request.user.selected_project.stats_cron = self.request.POST['cron']
            cron = croniter.croniter(self.request.user.selected_project.stats_cron, timezone.now())
            next_date = cron.get_next(datetime.datetime)
            self.request.user.selected_project.next_stats_fetch_time = next_date
        else:
            return '/stats?err=true'
        self.request.user.selected_project.save()
        return '/stats'
