import posixpath

from parallels.core.logging import get_logger
from parallels.core import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.connections.plesk_server import PleskServer
from parallels.core.runners.base import BaseRunner
from parallels.core.utils.config_utils import global_section
from parallels.plesk.hosting_repository.model import PleskHostingRepositoryModel

logger = get_logger(__name__)


class MigrateCourierToDovecot(SubscriptionAction):
    """Migrate Courier files to Dovecot, to avoid mail message re-download by POP3 clients

    For more details check issues PMT-3478 and PPP-4199, and read https://wiki.dovecot.org/Migration

    Known issue: conversion works incorrectly for the new mail messages received by the target server
    if we run mail re-sync, such messages will be re-downloaded by POP3 clients.
    """

    def get_description(self):
        """
        :rtype: str | unicode
        """
        return messages.MIGRATE_COURIER_TO_DOVECOT_ACTION_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.MIGRATE_COURIER_TO_DOVECOT_ACTION_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):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        if not self._is_enabled_in_config(global_context):
            return False

        source_server = subscription.mail_source_server
        if source_server is None or not isinstance(source_server, PleskServer) or source_server.is_windows():
            return False

        target_server = subscription.mail_target_server
        if target_server is None or not isinstance(target_server, PleskServer) or target_server.is_windows():
            return False

        if not self._has_mailboxes(subscription):
            return False

        source_hosting_repository = PleskHostingRepositoryModel(source_server)
        target_hosting_repository = PleskHostingRepositoryModel(target_server)

        source_components = source_hosting_repository.panel.get_installed_components(subscription.name)
        target_components = target_hosting_repository.panel.get_installed_components(subscription.name)

        courier_to_dovecot_migration = 'courier-imap' in source_components and 'dovecot' in target_components

        if not courier_to_dovecot_migration:
            return False

        return True

    def run(self, global_context, subscription):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        """
        target_server = subscription.mail_target_server

        maildir_migrate_bin = None
        for bin in ['/usr/lib64/plesk-9.0/maildir-migrate-dovecot', '/usr/lib/plesk-9.0/maildir-migrate-dovecot']:
            with target_server.runner() as runner:
                assert isinstance(runner, BaseRunner)
                if runner.file_exists(bin):
                    maildir_migrate_bin = bin

        if maildir_migrate_bin is None:
            logger.warn(messages.NO_MAILDIR_MIGRATE_BINARY)

        for domain in subscription.mail_converted_dump.iter_domains():
            if domain.mailsystem is None:
                continue

            for mailbox in domain.iter_mailboxes():
                with target_server.runner() as runner:
                    assert isinstance(runner, BaseRunner)

                    mailbox_dir = posixpath.join(
                        target_server.mail_dir, domain.name_idn,
                        mailbox.name.encode('idna')
                    )

                    if not runner.is_dir(mailbox_dir):
                        continue

                    runner.execute_command(
                        '{maildir_migrate_bin} --convert --to-dovecot --recursive --overwrite {mailbox_dir}',
                        dict(
                            maildir_migrate_bin=maildir_migrate_bin,
                            mailbox_dir=mailbox_dir
                        ),
                    )

    @staticmethod
    def _has_mailboxes(subscription):
        """
        :type subscription: parallels.core.migrated_subscription.MigratedSubscription
        :rtype: bool
        """
        for domain in subscription.mail_converted_dump.iter_domains():
            if domain.mailsystem is None:
                continue

            for _ in domain.iter_mailboxes():
                return True

        return False

    def _is_enabled_in_config(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: bool
        """
        return global_section(global_context.config).getboolean('courier-to-dovecot-migration', True)
