import os

from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.core.logging import get_logger
from parallels.core.reports.model.issue import Issue
from parallels.core.runners.base import BaseRunner
from parallels.core.utils.common import is_run_on_windows, safe_format
from parallels.core.utils.file_utils import get_relative_path
from parallels.plesk.source.web import messages
from parallels.plesk.source.web.actions.base.wordpress import WordPressApplicationAction

logger = get_logger(__name__)


class RegisterWordpress(WordPressApplicationAction):
    """Register migrated Wordpress instances in Wordpress Toolkit"""

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

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

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

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.ACTION_REGISTER_WORDPRESS_FAILURE

    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 get_failure_message_for_application(self, global_context, application):
        """Get message for situation when action failed for specific application

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type application: parallels.plesk.source.web.migrated_application.MigratedApplication
        :rtype: str | unicode | None
        """
        return safe_format(
            messages.ACTION_REGISTER_WORDPRESS_FAILURE_FOR_APP,
            path=application.target_path
        )

    def get_failure_severity_for_application(self):
        """Get issue severity for application in case if that action failed

        :rtype: str | unicode
        """
        return Issue.SEVERITY_WARNING

    def filter_for_application(self, global_context, application):
        """Check whether we should run this action for application or not. By default True - action should be executed.

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type application: parallels.plesk.source.web.migrated_application.MigratedApplication
        :rtype: None
        """
        return (
            super(RegisterWordpress, self).filter_for_application(global_context, application) and
            len(application.databases) > 0
        )

    def run_for_application(self, global_context, application):
        """Run action for single migrated application

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :type application: parallels.plesk.source.web.migrated_application.MigratedApplication
        :rtype: list[parallels.core.reports.model.issue.Issue] | None
        """
        hosting_repo = global_context.hosting_repository
        server = global_context.conn.target.plesk_server

        webspace_root = os.path.join(
            server.vhosts_dir, global_context.site_info_storage.get_target_subscription().encode('idna')
        )
        document_root = global_context.site_info_storage.get_target_document_root()
        is_windows = is_run_on_windows()
        relative_document_root = get_relative_path(
            document_root, webspace_root,
            is_windows=is_windows, sub_path_is_windows=is_windows, base_path_is_windows=is_windows
        )

        target_path = (
            os.sep + relative_document_root + os.sep + application.target_relative_path
        )

        subscription_info = hosting_repo.subscription.get_by_name(
            global_context.site_info_storage.get_target_subscription()
        )

        with global_context.conn.target.plesk_server.runner() as runner:
            assert isinstance(runner, BaseRunner)
            runner.execute_command('plesk ext wp-toolkit register -path {path} -domain-id {domain_id}', dict(
                path=target_path, domain_id=subscription_info.domain_id
            ))
            runner.execute_command('plesk ext wp-toolkit update-site-url -path {path} -main-domain-id {domain_id}', dict(
                path=target_path, domain_id=subscription_info.domain_id
            ))
