# -*- coding: utf-8 -*-
# Copyright (c) 2020 PyMiner Development Team <team@py2cn.com>
# 定义了pyminer主界面的一些常用操作
# 将路径和主界面设置为可以全局获取，有助于未来插件式开发更加简便。
import datetime
import logging
import os
import webbrowser

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import app2

version = 'v2.1.0 Beta'

_application = None
_root_dir = None
_main_window: 'app2.PMGWebBrowser' = None


def get_root_dir() -> str:
    """
    获取根路径。
    Returns:

    """
    # assert _root_dir is not None
    # return _root_dir
    return os.path.dirname(os.path.dirname(__file__))


def get_application() -> None:
    """
    获取QApplication
    Returns:

    """
    assert _application is not None
    return _application


def get_main_window() -> 'app2.MainWindow':
    """
    获取主窗口或者主控件。
    Returns:
    """
    return _main_window


def get_work_dir() -> 'str':
    """
    获取主窗口或者主控件。
    Returns:
    """
    from pyminer2.features.io.settings import Settings
    return Settings.get_instance()['work_dir']


def get_logger(name):
    """
    返回日志logger
    """
    log_folder = os.path.join(get_root_dir(), 'logs')
    if not os.path.exists(log_folder):
        os.mkdir(log_folder)

    logging_file = os.path.join(log_folder, f'log_{datetime.datetime.now().strftime("%Y-%m-%d")}.log')

    # 创建logger，如果参数为空则返回root logger
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)  # 设置logger日志等级
    # 创建handler
    fh = logging.FileHandler(logging_file, encoding="utf-8")  # 写入日志到文件中
    ch = logging.StreamHandler()  # 显示日志到控制台
    # 设置输出日志格式
    formatter = logging.Formatter(
        fmt="[%(asctime)s] %(levelname)-8s %(name)s [%(module)s:%(funcName)s:%(lineno)s] %(message)+8s",
        datefmt="%Y-%m-%d %X"
    )
    formatter.default_msec_format = '%s.%03d'

    # 为handler指定输出格式，注意大小写
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # 为logger添加的日志处理器
    logger.addHandler(fh)
    logger.addHandler(ch)
    return logger


def openURL(url):
    """
    打开网址
    """
    try:
        webbrowser.get('chrome').open_new_tab(url)
    except Exception as e:
        webbrowser.open_new_tab(url)


