#coding:utf8
import json

from django.db import models
from jsonfield import JSONField
from libs.cache import redis_client
from libs.error import logging_exception
from libs.types import ensure_str

# Create your models here.

class Strategy(models.Model):
    name = models.CharField(max_length=128, unique=True)
    desc = models.CharField(max_length=128, unique=True)
    json = JSONField()

    def __str__(self):
        return self.desc

    def push_search_cache(self):
        key = 'doris:strategy:%s' % self.name
        data = json.dumps(self.json)
        redis_client.set(key,data)

    @classmethod
    def get_strategy(cls, name):
        try:
            key = 'doris:strategy:%s' % name
            data = redis_client.get(key)
            data = ensure_str(data)
            if data is None:
                try:
                    obj = cls.objects.get(name=name)
                    data = json.dumps(obj.json)
                    redis_client.set(key,data)
                    return obj.json
                except cls.DoesNotExist:
                    return {}
            else:
                data = json.loads(data)
                return data
        except:
            import traceback
            traceback.print_exc()
            logging_exception()
            return {}


