# Path: apps/core/models.py
# class Service(models.Model):
#     """
#     denotes single sso client
#     - name:               unique name
#     - is_shown:           decides to show in SSO main page
#     - alias:              user friendly name
#     - scope:              scope; TEST / SPARCS / PUBLIC
#     - main_url:           main page url
#     - login_callback_url: login callback url
#     - unregister_url:     unregister page url
#     - secret_key:         secret key
#     - admin_user:         admin of this client
#     - cooltime:           cooltime (days) to re-register; < 60
#     - icon:               icon of this service
#     """
# 
#     name = models.CharField(max_length=40, primary_key=True)
#     is_shown = models.BooleanField(default=True)
#     alias = models.CharField(max_length=30)
#     scope = models.CharField(max_length=6, choices=SERVICE_SCOPE,
#                              default=SERVICE_TEST)
#     main_url = models.CharField(max_length=200)
#     login_callback_url = models.CharField(max_length=200)
#     unregister_url = models.CharField(max_length=200, null=True, blank=True)
#     secret_key = models.CharField(max_length=100)
#     admin_user = models.ForeignKey(User, on_delete=models.CASCADE,
#                                    related_name='managed_services')
#     cooltime = models.IntegerField()
#     icon = models.ImageField(null=True, blank=True)
# 
#     @property
#     def icon_url(self):
#         return self.icon.url if self.icon else '/static/img/test-service.png'
# 
#     def __str__(self):
#         return self.alias
# 
# class Statistic(models.Model):
#     """
#     denotes single statistic; raw json
#     - time: timestamp of statistic
#     - data: raw json statistic data
#     """
#     time = models.DateTimeField()
#     data = models.TextField()
# 
#     def pretty(self):
#         time_str = localtime(self.time).isoformat()
#         return f'{time_str} {self.data}'
# 
#     def __str__(self):
#         return f'{self.time}'


import json
from datetime import timedelta
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone
from apps.core.models import Service, Statistic
            elif 'P' in p_type:
                kaist_stat['professor'] += 1

    def handle(self, *args, **options):
        # get logs that over two month ago
        two_month = (timezone.now() - timedelta(days=60)) \
            .replace(hour=0, minute=0, second=0, microsecond=0)
        old_stats = Statistic.objects.filter(time__lt=two_month)
        with open(settings.STAT_FILE, 'a') as f:
            for old_stat in old_stats:
                f.write(old_stat.pretty() + '\n')
        old_stats.delete()

        # collect statistics of all services and all users
        services = list(map(lambda x: x.name,
                            Service.objects.all())) + ['all']
        users = User.objects.exclude(profile__expire_time__isnull=False) \
                            .exclude(profile__test_only=True)

        self.build_template(services)
        for user in users:
            services = list(map(lambda x: x.service.name,
                                filter(lambda x: not x.unregister_time,
                                       user.services.all()))) + ['all']
            for service in services:
                self.add_basic_stat(service, user)
                if user.profile.kaist_info:
                    kaist_info = json.loads(user.profile.kaist_info)
                    self.add_kaist_stat(service, kaist_info)


# Path: apps/core/models.py
# class Service(models.Model):
#     """
#     denotes single sso client
#     - name:               unique name
#     - is_shown:           decides to show in SSO main page
#     - alias:              user friendly name
#     - scope:              scope; TEST / SPARCS / PUBLIC
#     - main_url:           main page url
#     - login_callback_url: login callback url
#     - unregister_url:     unregister page url
#     - secret_key:         secret key
#     - admin_user:         admin of this client
#     - cooltime:           cooltime (days) to re-register; < 60
#     - icon:               icon of this service
#     """
# 
#     name = models.CharField(max_length=40, primary_key=True)
#     is_shown = models.BooleanField(default=True)
#     alias = models.CharField(max_length=30)
#     scope = models.CharField(max_length=6, choices=SERVICE_SCOPE,
#                              default=SERVICE_TEST)
#     main_url = models.CharField(max_length=200)
#     login_callback_url = models.CharField(max_length=200)
#     unregister_url = models.CharField(max_length=200, null=True, blank=True)
#     secret_key = models.CharField(max_length=100)
#     admin_user = models.ForeignKey(User, on_delete=models.CASCADE,
#                                    related_name='managed_services')
#     cooltime = models.IntegerField()
#     icon = models.ImageField(null=True, blank=True)
# 
#     @property
#     def icon_url(self):
#         return self.icon.url if self.icon else '/static/img/test-service.png'
# 
#     def __str__(self):
#         return self.alias
# 
# class Statistic(models.Model):
#     """
#     denotes single statistic; raw json
#     - time: timestamp of statistic
#     - data: raw json statistic data
#     """
#     time = models.DateTimeField()
#     data = models.TextField()
# 
#     def pretty(self):
#         time_str = localtime(self.time).isoformat()
#         return f'{time_str} {self.data}'
# 
#     def __str__(self):
#         return f'{self.time}'


# Path: apps/core/management/commands/collect-stats.py
import json
from datetime import timedelta
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone
from apps.core.models import Service, Statistic

            elif 'P' in p_type:
                kaist_stat['professor'] += 1

    def handle(self, *args, **options):
        # get logs that over two month ago
        two_month = (timezone.now() - timedelta(days=60)) \
            .replace(hour=0, minute=0, second=0, microsecond=0)
        old_stats = Statistic.objects.filter(time__lt=two_month)
        with open(settings.STAT_FILE, 'a') as f:
            for old_stat in old_stats:
                f.write(old_stat.pretty() + '\n')
        old_stats.delete()

        # collect statistics of all services and all users
        services = list(map(lambda x: x.name,
                            Service.objects.all())) + ['all']
        users = User.objects.exclude(profile__expire_time__isnull=False) \
                            .exclude(profile__test_only=True)

        self.build_template(services)
        for user in users:
            services = list(map(lambda x: x.service.name,
                                filter(lambda x: not x.unregister_time,
                                       user.services.all()))) + ['all']
            for service in services:
                self.add_basic_stat(service, user)
                if user.profile.kaist_info:
                    kaist_info = json.loads(user.profile.kaist_info)
                    self.add_kaist_stat(service, kaist_info)


        Statistic(time=timezone.now(), data=json.dumps(self.stats)).save()