"""
Determines hosting panel.
This module has minimal dependencies and only imports required panel class.
"""
import logging
from importlib import import_module
from pathlib import Path

CPANEL_FILE = "/usr/local/cpanel/cpanel"
DA_FILE = "/usr/local/directadmin/directadmin"
PLESK_FILE = "/usr/sbin/plesk"
GP_FILE = "/etc/sysconfig/imunify360/integration.conf"

logger = logging.getLogger(__name__)


def get_hosting_panel(root_module: str):  # pragma no cover
    # note: keep the panel test order in sync with the deploy script,
    #   to avoid detecting conflicting panels in agent vs. the deploy script
    if is_generic_panel_installed():
        # Checking this panel first is convenient for development, since
        # it allows you to turn any panel in the Generic Panel simply by
        # creating `/etc/sysconfig/imunify360/integration.conf`.
        module = import_module(f"{root_module}.subsys.panels.generic.panel")

        return module.GenericPanel()
    elif is_plesk_installed():
        module = import_module(f"{root_module}.subsys.panels.plesk.panel")

        return module.Plesk()
    elif is_cpanel_installed():
        module = import_module(f"{root_module}.subsys.panels.cpanel.panel")

        return module.cPanel()
    elif is_directadmin_installed():
        module = import_module(
            f"{root_module}.subsys.panels.directadmin.panel"
        )

        return module.DirectAdmin()
    elif root_module == "defence360agent":
        module = import_module(f"{root_module}.subsys.panels.no_cp.panel")

        return module.NoCP()

    module = import_module(f"{root_module}.subsys.panels.no_cp.panel")

    return module.NoControlPanel()


def is_cpanel_installed():
    return _is_panel_installed(CPANEL_FILE)


def is_directadmin_installed():
    return _is_panel_installed(DA_FILE)


def is_generic_panel_installed():
    return _is_panel_installed(GP_FILE)


def is_plesk_installed():
    return _is_panel_installed(PLESK_FILE)


def _is_panel_installed(panel_file):
    return Path(panel_file).is_file()
