from parallels.core.logging import get_logger
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.runners.base import BaseRunner
from parallels.core.utils.common import exists
from parallels.plesk import messages
from parallels.plesk.hosting_repository.model import PleskHostingRepositoryModel
from parallels.plesk.source.plesk.server import PleskSourceServer

logger = get_logger(__name__)


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

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

    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.ACTION_TRANSFER_TOMCAT_APPLICATIONS_FAILURE

    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):
        """Check if we should run this action on given subscription or not

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: bool
        """
        target_hosting_repository = PleskHostingRepositoryModel(subscription.web_target_server)
        target_components = target_hosting_repository.panel.get_installed_components(subscription.name)
        if not exists(target_components, lambda component: component.startswith('tomcat')):
            return False

        domains = subscription.converted_dump.iter_domains()
        if not exists(domains, lambda domain: len(domain.tomcat_applications) > 0):
            return False

        return True

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

        :type global_context: parallels.plesk.source.plesk.global_context.PleskGlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: None
        """
        source_server = subscription.web_source_server
        target_server = subscription.web_target_server

        assert isinstance(source_server, PleskSourceServer)

        for domain in subscription.converted_dump.iter_domains():
            existing_applications = global_context.hosting_repository.tomcat.list_applications(
                subscription.name, domain.name
            )
            existing_application_names = {app.application_name for app in existing_applications}

            for tomcat_application in domain.tomcat_applications:
                if tomcat_application.name in existing_application_names:
                    logger.fdebug(
                        messages.SKIP_RESTORE_EXISTING_TOMCAT_APPLICATION,
                        domain=domain.name, application_name=tomcat_application.name
                    )
                    continue
                else:
                    logger.fdebug(
                        messages.RESTORE_TOMCAT_APPLICATION,
                        domain=domain.name, application_name=tomcat_application.name
                    )

                source_application_file = source_server.join_path(
                    source_server.tomcat_dir, 'psa-wars', domain.name_idn, "%s.war" % tomcat_application.name
                )
                local_applications_dir = global_context.session_files.get_path_to_tomcat_applications_dir(
                    domain.name_idn
                )
                with global_context.migrator_server.runner() as runner:
                    runner.mkdir(local_applications_dir)
                local_application_file = global_context.migrator_server.join_file_path(
                    local_applications_dir, '%s.war' % tomcat_application.name
                )

                with source_server.runner() as runner:
                    assert isinstance(runner, BaseRunner)
                    runner.get_file(source_application_file, local_application_file)

                target_applications_dir = target_server.get_session_file_path(
                    target_server.join_path('tomcat', domain.name_idn)
                )
                target_application_file = target_server.join_file_path(
                    target_applications_dir, '%s.war' % tomcat_application.name
                )
                with target_server.runner() as runner:
                    assert isinstance(runner, BaseRunner)
                    runner.mkdir(target_applications_dir)
                    runner.upload_file(local_application_file, target_application_file)

                with global_context.migrator_server.runner() as runner:
                    assert isinstance(runner, BaseRunner)
                    runner.remove_file(local_application_file)

                global_context.hosting_repository.tomcat.install_application(
                    subscription.name, domain.name, target_application_file
                )

                with target_server.runner() as runner:
                    assert isinstance(runner, BaseRunner)
                    runner.remove_file(target_application_file)
