from parallels.core.panels import load_target_panel_class, load_source_panel_class
from parallels.core.workflow.base_workflow import BaseWorkflow
from parallels.core.workflow.builder import WorkflowBuilderBase
from parallels.core.workflow.shared_hosting_workflow import SharedHostingWorkflowExtension


class DefaultWorkflowBuilder(WorkflowBuilderBase):
    def create_workflow(self, global_context):
        """Create and return workflow object according given context

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: parallels.core.workflow.base_workflow.BaseWorkflow
        """
        # Situation #1: build workflow by source panel - if it has custom workflow builder
        if global_context.source_panel_type is not None:
            source_workflow_builder_class = load_source_panel_class(
                global_context.source_panel_type, 'workflow', 'WorkflowBuilder', optional=True
            )
            if source_workflow_builder_class is not None:
                source_workflow_builder = source_workflow_builder_class()
                assert isinstance(source_workflow_builder, WorkflowBuilderBase)
                return source_workflow_builder.create_workflow(global_context)

        # Situation #2: build workflow by shared hosting workflow + target extension + source extension
        workflow = BaseWorkflow()
        shared_hosting_extension = SharedHostingWorkflowExtension()
        shared_hosting_extension.extend_workflow(workflow)

        if global_context.target_panel_type is not None:
            # extend workflow with target-panel specific actions
            target_panel_workflow_class = load_target_panel_class(
                global_context.target_panel_type, 'workflow', 'WorkflowExtension'
            )
            target_workflow_extension = target_panel_workflow_class()
            target_workflow_extension.extend_workflow(workflow)

        if global_context.source_panel_type is not None:
            # extend workflow with source-panel specific actions
            source_workflow_extension_class = load_source_panel_class(
                global_context.source_panel_type, 'workflow', 'WorkflowExtension'
            )
            source_workflow_extension = source_workflow_extension_class()
            source_workflow_extension.extend_workflow(workflow)

        return workflow
