from parallels.core import get_logger
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.utils.dsn.dsn import DsnCommand
from parallels.plesk.source.plesk import messages

logger = get_logger(__name__)


class FixOdbcDsnConnectionStatus(SubscriptionAction):
    """Fix ODBC DSN connection status.
    """

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

        :rtype: str | unicode
        """
        return messages.ACTION_FIX_ODBC_DSN_CONNECTION_STATUS_DESCRIPTION

    def get_failure_message(self, global_context, subscription):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: str | unicode
        """
        return messages.ACTION_FIX_ODBC_DSN_CONNECTION_STATUS_FAILED.format(subscription_name=subscription.name)

    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(compound=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 filter_subscription(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        return subscription.converted_dump.odbc_dsns

    def run(self, global_context, subscription):
        """Run action on given subscription

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        for odbc_dsn in subscription.converted_dump.odbc_dsns:
            dsn = DsnCommand(subscription.web_target_server)
            dsn_info = dsn.xml_info(odbc_dsn.name)
            if dsn_info.configured == 'false' and dsn_info.connection_string != '':
                dsn.update_connection_string(odbc_dsn.name, dsn_info.connection_string)
