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

import json

from rpc.cache import gadget_cache
from api.models.app_config.v1 import AppConfig
from gm_types.gaia import AppConfigValueType
from datetime import datetime


class StartupProcess(object):
    """
    App启动流程配置
    """

    RKEY_PREFIX = 'start_up_process'
    CONFIG_NAME = 'App启动流程配置'
    CONFIG_KEY = 'startup_process'

    DEFAULT_DEPLOY = {
        'grayscale': False,
        "configs": {
            "information": {
                "status": False,
                "sort": 2,
            },
            "problem": {
                "status": False,
                "sort": 3,
            },
            "AI_animation": {
                "status": False,
                "sort": 4,
            },
            "daily_check": {
                "status": False,
                "sort": 5,
                "url": "",
            },
        },
        "rookie_coupon": {  # 新手券
            "status": False,
            "id": 0,   # 券ID
        },
        'introduce_pic': {
            "status": False,
            "image": "",
            "image_ipx": "",  # iphoneX版本类大图
        }
    }

    @classmethod
    def get_start_up_process_deploy(cls):
        res = gadget_cache.get(cls.RKEY_PREFIX)
        if not res:
            res = cls.update_cache()

        res = json.loads(res or "{}")
        if not res:
            res = cls.DEFAULT_DEPLOY

        for key in set(cls.DEFAULT_DEPLOY['configs'].keys()) - set(res['configs'].keys()):
            res['configs'].setdefault(key, cls.DEFAULT_DEPLOY['configs'][key])

        for key in set(cls.DEFAULT_DEPLOY.keys()) - set(res.keys()):
            res[key] = cls.DEFAULT_DEPLOY[key]

        return res

    @classmethod
    def set_start_up_process_deploy(cls, deploy_info):
        try:
            gadget_cache.set(cls.RKEY_PREFIX, deploy_info)
        except:
            pass

    @classmethod
    def get_startup_process_config(cls):
        try:
            return AppConfig.objects.get(name=cls.CONFIG_NAME).value
        except:
            res = ""
        return res

    @classmethod
    def update_cache(cls):
        res = cls.get_startup_process_config()
        if res:
            cls.set_start_up_process_deploy(res)
        return res

    @classmethod
    def update_app_config(cls, config):
        AppConfig.objects.update_or_create(
            name=cls.CONFIG_NAME,
            defaults={
                "key": cls.CONFIG_KEY,
                "value": config,
                "value_type": AppConfigValueType.TYPE_JSON,
                "is_online": True,
                "online_time": datetime.now(),
                "offline_time": datetime.now(),
            }
        )

        cls.set_start_up_process_deploy(config)