import os

import parallels
from parallels.core.logging import get_logger
from parallels.core.utils import migrator_utils
from parallels.core.utils.common import cached
from parallels.plesk.source.plesk.pmm_agent.unix import PleskXPmmMigrationAgent
from parallels.plesk.source.plesk.pmm_agent.windows import WindowsPleskPmmMigrationAgent

logger = get_logger(__name__)


@cached
def create_pmm_agent(global_context, source_server):
    """Initialize and return instance of PmmMigrationAgentBase.

    :type global_context: parallels.core.global_context.GlobalMigrationContext
    :type source_server: parallels.plesk.source.plesk.server.PleskSourceServer
    :rtype: parallels.core.utils.pmm.agent.PmmMigrationAgentBase
    """

    if source_server.is_windows():
        agent = WindowsPleskPmmMigrationAgent(global_context, source_server)
    else:
        migrator_pmm_dir = migrator_utils.get_package_extras_file_path(
            parallels.plesk.source.plesk, get_pmm_agent_dir(source_server)
        )
        agent = PleskXPmmMigrationAgent(
            global_context,
            source_server,
            migrator_pmm_dir,
            PleskPMMConfig(source_server.node_settings)
        )

    global_context.deployed_dump_agents.append(agent)

    return agent


def get_pmm_agent_dir(source_server):
    """
    :type source_server: parallels.plesk.source.plesk.server.PleskSourceServer
    :rtype: str
    """
    source_plesk_version = source_server.plesk_version
    if source_plesk_version < (17, 0):
        return 'pmm_12_5'
    else:
        return 'pmm_17_0'


class PleskPMMConfig(object):
    def __init__(self, settings):
        self.ip = settings.ip
        self.id = settings.id
        self.is_windows = settings.is_windows
        self.ssh_auth = settings.ssh_auth
        self.session_dir = settings.session_dir
        self.agent_home = os.path.join(self.session_dir, 'migration_agent')
        self.pmm_agent_name = "PleskX"
        self.agent_script_name = 'PleskX.pl'
