import time

from parallels.core import get_logger
from parallels.core.actions.utils.logging_properties import LoggingProperties
from parallels.plesk.source.web import messages
from parallels.plesk.source.web.actions.base.site_migration import SiteMigrationAction
from parallels.plesk.source.web.utils.statistics import safe_calc_data_size

logger = get_logger(__name__)


class FinalizeTransferSiteStatistics(SiteMigrationAction):
    """Update statistics for 'transfer-site' command and save it to file
    """

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

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

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

    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_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, compound=False)

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

        Arguments:
        - global_context - registry with different objects that reused among different actions

        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        :rtype: bool
        """
        return global_context.statistics_transfer_site is not None

    def run(self, global_context):
        """
        :type global_context: parallels.plesk.source.web.global_context.WebGlobalMigrationContext
        """
        stat = global_context.statistics_transfer_site

        stat.end_time = int(time.time())
        stat.php_version = global_context.site_info_storage.get_php_version()
        stat.ftp_version = global_context.site_info_storage.get_ftp_version()
        stat.target_domain_name = global_context.site_info_storage.get_target_domain_name()
        stat.target_domain_type = global_context.site_info_storage.get_target_domain_type()
        stat.source_domain_name = global_context.site_info_storage.get_site_name()
        stat.source_is_windows = global_context.site_info_storage.get_is_windows()
        with safe_calc_data_size():
            stat.db_size += global_context.db_dumps_size

        stat.write()
