import os

from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.migrator_config import read_event_scripts_dir
from parallels.core.runners.base import BaseRunner

logger = get_logger(__name__)


class RunSubscriptionMigrationFinishedScripts(SubscriptionAction):
    def get_description(self):
        """Get short description of action as string

        :rtype: str
        """
        return messages.ACTION_RUN_SUBSCRIPTION_FINISHED_SCRIPTS

    def get_failure_message(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return messages.FAILURE_RUN_SUBSCRIPTION_FINISHED_SCRIPTS

    def get_logging_properties(self):
        """Get how action should be logged to migration tools end-user

        :rtype: parallels.core.actions.utils.logging_properties.LoggingProperties
        """
        return LoggingProperties(info_log=False)

    def is_critical(self):
        """If action is critical or not

        If action is critical and it failed for a subscription, migration tool
        won't run the next operations for the subscription.

        :rtype: bool
        """
        return False

    def run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        scripts_dir = os.path.join(
            read_event_scripts_dir(global_context.config),
            'subscription-migration-finished'
        )
        logger.debug(messages.LOG_SUBSCRIPTION_FINISHED_SCRIPT_DIR.format(scripts_dir=scripts_dir))

        if os.path.isdir(scripts_dir):
            for filename in os.listdir(scripts_dir):
                full_path = os.path.join(scripts_dir, filename)
                if os.path.isfile(full_path):
                    with global_context.migrator_server.runner() as runner:
                        assert isinstance(runner, BaseRunner)
                        logger.info(messages.LOG_RUN_SUBSCRIPTION_FINISHED_SCRIPT.format(
                            script=full_path, subscription=subscription.name
                        ))
                        runner.execute_command("{script} {subscription}", dict(
                            script=full_path, subscription=subscription.name
                        ))
