#!/usr/bin/env python
# -*- coding: utf-8 -*-

from api.models.app_config.v1 import AppConfig
from datetime import datetime


class APPConfigCache(object):
    """
    appconfig
    """
    PUSH_AUTHORIZATION_GIFT = 'push_authorization_gift'     # push授权礼包

    def __init__(self, cache, config_key):
        self.cache = cache
        self.config_key = config_key

    def get_config_from_cache(self):
        res = self.cache.get(self.config_key)
        if not res:
            res = self.update_cache()
        return res

    def set_config_cache(self, config):
        self.cache.set(self.config_key, config)

    def get_config_value_from_mysql(self):
        try:
            return AppConfig.objects.get(key=self.config_key).value
        except:
            res = ""
        return res

    def update_cache(self):
        res = self.get_config_value_from_mysql()
        if res:
            self.set_config_cache(res)
        return res

    def update_app_config(self, value, value_type, name, is_online=True, online_time=datetime.now(),
                          offline_time=datetime.now()):
        AppConfig.objects.update_or_create(
            key=self.config_key,
            defaults={
                "name": name,
                "value": value,
                "value_type": value_type,
                "is_online": is_online,
                "online_time": online_time,
                "offline_time": offline_time,
            }
        )
