from parallels.core import messages
from parallels.core.utils.common import safe_format, is_empty
from parallels.core.runners.exceptions.base import BaseRunnerException


class MSSQLException(BaseRunnerException):
    def __init__(self, message, code=None, connection_settings=None, query=None, args=None, connected_from=None):
        """
        :type message: str | unicode
        :type code: str | unicode | None
        :type connection_settings: parallels.core.runners.entities.MSSQLConnectionSettings
        :type query: str | unicode
        :type args: dict | None
        :type connected_from: str | unicode | None
        """
        message_parts = [
            safe_format(messages.SQL_QUERY_FAILED, reason=message)
        ]
        if query is not None:
            message_parts.append(safe_format(messages.SQL_QUERY_QUERY, query=query))
        if args is not None and len(args) > 0:
            message_parts.append(safe_format(messages.SQL_QUERY_ARGUMENTS, arguments=repr(args)))
        if connection_settings is not None and not is_empty(connection_settings.database):
            message_parts.append(safe_format(messages.SQL_QUERY_DATABASE, user=connection_settings.database))
        if connection_settings is not None and not is_empty(connection_settings.host):
            message_parts.append(safe_format(messages.SQL_QUERY_SERVER, server=connection_settings.host))
        if connection_settings is not None and not is_empty(connection_settings.user):
            message_parts.append(safe_format(messages.SQL_QUERY_USER, user=connection_settings.user))
        if not is_empty(connected_from):
            message_parts.append(safe_format(messages.SQL_QUERY_CONNECTED_FROM, server=connected_from))

        message_parts.append(u"")  # empty line before solution
        message_parts.append(messages.SQL_QUERY_SOLUTION)

        super(MSSQLException, self).__init__("\n".join(message_parts))
        self._code = code

    @property
    def code(self):
        return self._code
