from parallels.core.logging import get_logger
from parallels.core.utils.common import is_run_on_windows
from parallels.core.utils.plesk_utils import recalculate_mailbox_maildir_size_linux, update_mail_usage_stats
from parallels.plesk.source.mail import messages
from parallels.plesk.source.mail.actions.base.mail_migration import MailMigrationAction

logger = get_logger(__name__)


class RefreshDiskUsage(MailMigrationAction):
    """Read site migration list - with selected applications, files and databases to migrate"""

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

        :rtype: str | unicode
        """
        return messages.ACTION_REFRESH_DISK_USAGE_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_REFRESH_DISK_USAGE_FAILURE

    def run(self, global_context):
        """Run action

        :type global_context: parallels.plesk.source.mail.global_context.MailGlobalMigrationContext
        """
        mail_address_pair = global_context.migrated_mail_address_pair
        migrator_server = global_context.migrator_server
        with migrator_server.runner() as runner:
            if not is_run_on_windows():
                # After migration of mail content we have to recalculate mail usage in
                # "maildirsize" file of mail directory. Otherwise, we could get
                # incorrect mail usage in the control panel, and mail quota limitations
                # could work incorrectly.
                # On Linux recalculation is not performed automatically
                # when update mail usage stats is called (see below), so we have to
                # call Plesk backend directly
                mailbox_quota = global_context.hosting_repository.mail_account.get_mailbox_effective_quota(
                    global_context.target_subscription_name,
                    mail_address_pair.target_mailname, mail_address_pair.target_domain
                )
                recalculate_mailbox_maildir_size_linux(
                    runner, mail_address_pair.target_domain, mail_address_pair.target_mailname, mailbox_quota
                )

            update_mail_usage_stats(runner, mail_address_pair.target_subscription_name)
