import os

from parallels.core import safe_format
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.plesk.source.web import messages
from parallels.plesk.source.web.actions.base.application import ApplicationAction

logger = get_logger(__name__)


class RemoveIndexFiles(ApplicationAction):
    """Remove unnecessary index files"""

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

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

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

        If action is critical and it failed, migration tool completely stops.
        Otherwise it proceeds to the next steps of migrations.

        :rtype: bool
        """
        return False

    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_REMOVE_INDEX_FILES_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 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_REMOVE_INDEX_FILES_FAILURE_FOR_APP,
            application_type=application.application_model.name,
            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 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
        """
        index_files = ['index.html']

        document_root = global_context.site_info_storage.get_target_document_root()
        for index_file in index_files:
            index_file = os.path.join(document_root, application.target_path, index_file)
            if os.path.isfile(index_file):
                plesk_dir = global_context.conn.target.plesk_server.plesk_dir
                filemng = os.path.join(plesk_dir, 'admin', 'bin', 'filemng')
                user = global_context.site_info_storage.get_target_sysuser_login()
                logger.fdebug(messages.INDEX_FILE_REMOVED, file=index_file)
                with global_context.conn.target.plesk_server.runner() as runner:
                    assert isinstance(runner, BaseRunner)
                    runner.execute_command('{filemng} {user} rm {index_file}', dict(
                        filemng=filemng, user=user, index_file=index_file
                    ))
