from parallels.core.utils.common import default


def get_mailbox_temp_directory(server, domain, mailbox):
    """Get path to a directory with temporary files to copy messages of mailbox

    :type server: parallels.core.connections.server.Server
    :type domain: parallels.core.dump.data_model.Domain
    :type mailbox: parallels.core.dump.data_model.Mailbox
    :rtype: str | unicode
    """
    return server.get_session_file_path(
        server.join_file_path('mail', domain.name.encode('idna'), mailbox.name.encode('idna'))
    )


def write_account_description_file(
    server, domain, mailbox, filename,
    override_mailname=None, override_domain=None, override_password=None,
    convert_to_lowercase=False
):
    """Write file describing mailbox for MailMigrator to specified filename on specified server

    :type server: parallels.core.connections.server.Server
    :type domain: parallels.core.dump.data_model.Domain
    :type mailbox: parallels.core.dump.data_model.Mailbox
    :type filename: str | unicode
    :type override_mailname: str | unicode | None
    :type override_domain: str | unicode | None
    :type override_password: str | unicode | None
    :type convert_to_lowercase: bool
    :rtype: None
    """
    domain_name = domain.name.encode('idna') if override_domain is None else override_domain
    if convert_to_lowercase:
        domain_name = domain_name.lower()
    mailbox_name = mailbox.name if override_mailname is None else override_mailname
    if convert_to_lowercase:
        mailbox_name = mailbox_name.lower()
    password = mailbox.password.password_text if override_password is None else override_password

    mailbox_description_contents = "\n".join([domain_name, mailbox_name, password])
    with server.runner() as runner:
        runner.upload_file_content(filename, mailbox_description_contents)


def write_account_description_file_plain(
    server, filename,
    mailname, domain, password=None,
    convert_to_lowercase=False
):
    """Write file describing mailbox for MailMigrator to specified filename on specified server

    :type server: parallels.core.connections.server.Server
    :type filename: str | unicode
    :type mailname: str | unicode
    :type domain: str | unicode
    :type password: str | unicode | None
    :type convert_to_lowercase: bool
    :rtype: None
    """
    domain = domain.encode('idna')

    if convert_to_lowercase:
        mailname = mailname.lower()

    if isinstance(mailname, unicode):
        mailname = mailname.encode('utf-8')
    if isinstance(password, unicode):
        password = password.encode('utf-8')

    mailbox_description_contents = "\n".join([domain, mailname, default(password, '')])
    with server.runner() as runner:
        runner.upload_file_content(filename, mailbox_description_contents)
