# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import

import os
from django.apps import AppConfig
from django.conf import settings


class RPCAppConfig(AppConfig):

    name = 'rpc'
    verbose_name = "RPC"

    def ready(self):
        initialize()
        # 如果是 celery worker 启动，则不在这里初始化 AppConfig
        if os.environ.get("DJANGO_CELERY_MODE") != "TRUE":
            initialize_gm_logging()


def initialize():

    from . import instance
    from . import urls
    from . import vendor_methods

    import api.tasks.push_task

    import utils.data_sync.impl

    import_views_in_apps()

    instance.api_manager.freeze()


def initialize_gm_logging():
    """ 初始化 gm-logging """
    # check version of gm_logging
    # TODO: 暂时没想法
    from distutils.version import LooseVersion
    required_version = '0.2.6'
    message = 'gm_logging>={} required'.format(required_version)
    try:
        from gm_logging.version import VERSION
    except ImportError:
        raise Exception(message)
    if LooseVersion(VERSION) < LooseVersion(required_version):
        raise Exception(message)
    # end check version

    import gm_logging.gm_rpcd
    gm_logging.gm_rpcd.configure(
        log_basedir=settings.LOG_DIR,
        log_prefix='gaia',
        log_buffered=not settings.DEBUG,
    )
    from .tool.log_tool import setup_elasticsearch_logging  # 确保能被初始化
    from .tool.log_tool import setup_message_trace_logging  # 初始化私信链路日志
    setup_message_trace_logging()


def import_views_in_apps():
    from django.conf import settings
    from os.path import basename, dirname, splitext, join, isdir, isfile, commonprefix, abspath
    import importlib
    import gaia
    from rpc.tool.log_tool import info_logger

    assert splitext(basename(gaia.__file__))[0] == '__init__'       # expect .../gaia/gaia/__init__.py
    project_basedir = dirname(dirname(abspath(gaia.__file__)))      # expect .../gaia
    info_logger.info('gaia project basedir: {}'.format(project_basedir))

    for app_import_path in settings.INSTALLED_APPS:
        app_dir_path = join(project_basedir, *app_import_path.split('.'))

        if not isfile(join(app_dir_path, 'views.py')) and not isfile(join(app_dir_path, 'views', '__init__.py')):
            info_logger.info('ignore .views from {} @ {}'.format(app_import_path, app_dir_path))
            continue

        info_logger.info('import .views from {} @ {}'.format(app_import_path, app_dir_path))

        views_module = importlib.import_module('.views', app_import_path)   # do import

        # check views_module path
        if commonprefix([abspath(views_module.__file__), app_dir_path]) != app_dir_path:
            raise Exception('module {}.views does not locate in {}'.format(
                app_import_path,
                app_dir_path,
            ))
