from typing import TYPE_CHECKING
from urllib.request import getproxies

from fuo_ytmusic.language import resolve_language

if TYPE_CHECKING:
    from feeluown.app import App

__alias__ = "ytmusic"
__version__ = "0.4.18"
__desc__ = "YouTube Music plugin"


ui_mgr = None


def init_config(config):
    # For example: http://127.0.0.1:7890. This will be used in API and media accessing.
    config.deffield("HTTP_PROXY", type_=str, default="", desc="YouTube Music HTTP proxy")
    config.deffield("HTTP_TIMEOUT", type_=int, default=2, desc="HTTP requests timeout")
    config.deffield(
        "LANGUAGE",
        type_=str,
        default="auto",
        desc="YouTube Music language (auto to follow system)",
    )


def enable(app: "App"):
    global ui_mgr

    from fuo_ytmusic.provider import provider

    # Use system http proxy by default.
    sys_proxies = getproxies()
    sys_http_proxy = sys_proxies.get("http")
    config_http_proxy = app.config.ytmusic.HTTP_PROXY
    if not config_http_proxy and sys_http_proxy:
        config_http_proxy = sys_http_proxy

    provider.setup_http_proxy(config_http_proxy)
    provider.setup_http_timeout(app.config.ytmusic.HTTP_TIMEOUT)
    provider.setup_language(resolve_language(app, app.config.ytmusic.LANGUAGE))
    app.library.register(provider)
    if app.mode & app.GuiMode:
        from .provider_ui import ProviderUI

        provider_ui = ProviderUI(app)
        app.pvd_ui_mgr.register(provider_ui)


def disable(app: "App"):
    global ui_mgr

    provider = app.library.get("ytmusic")
    if provider is not None:
        app.library.deregister(provider)
    ui_mgr = None
