import logging

from django.contrib.postgres.fields import JSONField
from django.db import models

from idm.core.querysets.systemmetainfo import SystemMetainfoManager

log = logging.getLogger(__name__)


class SystemMetainfoMetaclass(models.base.ModelBase):
    def __new__(typ, name, bases, attrs):
        trackable_tasks = attrs['TRACKABLE_TASKS']
        for task in trackable_tasks:
            attrs['last_{}_start'.format(task)] = models.DateTimeField(null=True, blank=True)
            attrs['last_{}_finish'.format(task)] = models.DateTimeField(null=True, blank=True)
            attrs['monitor_{}'.format(task)] = models.BooleanField(default=True)
        return super(SystemMetainfoMetaclass, typ).__new__(typ, name, bases, attrs)



class SystemMetainfo(models.Model, metaclass=SystemMetainfoMetaclass):
    """Информация о прошедших периодических тасках для системы"""

    # Таски, для каждой из которой создаются поля last_{task}_start, last_{task}_finish, ignore_{task}
    TRACKABLE_TASKS = [
        'sync_nodes',
        'deprive_nodes',
        'check_inconsistencies',
        'report_inconsistencies',
        'resolve_inconsistencies',
        'activate_memberships',
        'deprive_memberships',
        'update_memberships',
        'check_memberships',
        'resolve_memberships',
        'recalc_pipeline',
    ]

    objects = SystemMetainfoManager()

    roles_failed_on_last_review = JSONField(null=True, blank=True)

    def __repr__(self):
        return '<SystemMetainfo: {}>'.format(self.system.slug)

