from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from core.orm.model import BaseModel
from django.core.cache import cache


class Task(BaseModel):
    name = models.CharField(max_length=200, null=True)
    instrument = models.CharField(max_length=200)
    instrument_name = models.CharField(max_length=200, null=True)
    emails = ArrayField(models.CharField(max_length=200, blank=True), verbose_name='通知邮箱')
    config = JSONField()

    @property
    def code(self):
        pass

    @property
    def max_val(self):
        pass

    @property
    def min_val(self):
        pass

    @property
    def type(self):
        pass

    @staticmethod
    def set_active_list(instrument):
        active_list = Task.objects.filter(instrument=instrument, active=True)
        dd = []
        for al in active_list:
            d = {'id': al.pk, 'instrument': al.instrument, 'name': al.instrument_name, 'emails': list(al.emails),
                 'type': al.config.get('type'), 'max_val': str(al.config.get('max_val')),
                 'min_val': str(al.config.get('min_val'))}
            dd.append(d)
        cache.set(instrument, dd)

    @staticmethod
    def get_active_list(instrument):
        active_list = cache.get(instrument)
        return active_list if active_list else []

    @staticmethod
    def remove_task(task):
        Task.objects.filter(pk=int(task.get('id'))).update(active=False)
        Task.set_active_list(task.get('instrument'))


class TaskNotify(BaseModel):
    task_id = models.IntegerField()
    point = models.CharField(max_length=200)

    class Meta:
        ordering = ['-id']
        unique_together = ('task_id', 'point')