from xml.etree import ElementTree

from parallels.core.runners.base import BaseRunner
from parallels.core.utils.plesk_utils import get_windows_util_path


class DsnCommand(object):
    """Wrapper around "dsn.exe" command"""

    def __init__(self, server):
        """
        :param parallels.core.connections.plesk_server.PleskServer server:
        """
        self._server = server

    def xml_info(self, name):
        """Call "dsn.exe --xml-info" for specified ODBC DSN name

        :param str|unicode name: ODBC DSN name
        :return: DsnXmlInfoResult
        """
        with self._server.runner() as runner:
            assert isinstance(runner, BaseRunner)
            stdout = runner.execute_command(
                u'{dsn_bin} --xml-info {name}',
                dict(
                    dsn_bin=self._dsn_bin,
                    name=name
                )
            ).stdout

        return DsnXmlInfoResult(stdout)

    def update_connection_string(self, name, connection_string):
        """Call "dsn.exe --update" for specified ODBC DSN name and connection string

        :param str|unicode name: ODBC DSN name
        :param str|unicode connection_string: str|unicode
        :return: str|unicode
        """
        with self._server.runner() as runner:
            assert isinstance(runner, BaseRunner)
            stdout = runner.execute_command(
                u'{dsn_bin} --update {name} -connection_string {connection_string}',
                dict(
                    dsn_bin=self._dsn_bin,
                    name=name,
                    connection_string=connection_string
                )
            ).stdout

        return stdout

    @property
    def _dsn_bin(self):
        """Get full path to dsn.exe binary"""
        with self._server.runner() as runner:
            return get_windows_util_path(runner, 'dsn.exe')


class DsnXmlInfoResult(object):
    def __init__(self, response_str):
        """
        :type response_str: str
        """
        self._response_str = response_str
        self._xml = ElementTree.fromstring(response_str)

    @property
    def configured(self):
        return self._xml.findtext('configured')

    @property
    def connection_string(self):
        return self._xml.findtext('connection-string')
