from parallels.core.workflow.extension import WorkflowExtensionBase
from parallels.plesk.workflow import WorkflowExtension as PleskWorkflowExtension
from parallels.plesk_multi_server.actions.convert_ips_and_nodes import ConvertIPsAndNodesAction
from parallels.plesk_multi_server.actions.remove_ssh_keys import RemoveServiceNodesSSHKeys


class WorkflowExtension(WorkflowExtensionBase):
    def extend_workflow(self, workflow):
        """Extend shared hosting workflow with source-panel specific actions

        :type workflow: parallels.core.workflow.base_workflow.BaseWorkflow
        """
        PleskWorkflowExtension().extend_workflow(workflow)

        # Create customers and subscriptions before convert hosting:
        # that is required to know the exact node to which subscription is provisioned to
        # perform IP replacements in backup dump file correctly.
        deploy_customers = workflow.get_path('transfer-accounts/deploy/deploy-customers')
        deploy_subscriptions = workflow.get_path('transfer-accounts/deploy/deploy-subscription')
        deploy_plans = workflow.get_path('transfer-accounts/deploy/deploy-plans')
        workflow.get_path('transfer-accounts/deploy').remove_actions([
            'deploy-customers', 'deploy-subscription', 'deploy-plans'
        ])
        workflow.get_path('transfer-accounts').insert_action(
            'deploy-plans', deploy_plans, before='convert-hosting'
        )
        workflow.get_path('transfer-accounts').insert_action(
            'deploy-customers', deploy_customers, before='convert-hosting'
        )
        workflow.get_path('transfer-accounts').insert_action(
            'deploy-subscription', deploy_subscriptions, before='convert-hosting'
        )

        # Create customer and subscription when running pre-migration checks. That could be confusing,
        # but that is the only obvious way to perform per target service node check for subscriptions.
        workflow.get_path('check/prepare-assets').insert_action(
            'deploy-plans', deploy_plans, before='convert-hosting'
        )
        workflow.get_path('check/prepare-assets').insert_action(
            'deploy-customers', deploy_customers, before='convert-hosting'
        )
        workflow.get_path('check/prepare-assets').insert_action(
            'deploy-subscription', deploy_subscriptions, before='convert-hosting'
        )

        workflow.get_shared_action('convert').remove_action('convert-ip-addresses')
        workflow.get_shared_action('convert').insert_action(
            'convert-ips-and-nodes', ConvertIPsAndNodesAction(), after='convert-clients-and-subscriptions'
        )

        workflow.get_shared_action('cleanup').insert_action(
            'remove-ssh-keys', RemoveServiceNodesSSHKeys()
        )
