from xml.etree import ElementTree

from persistence import Connection


class Driver(object):
    conn_string = None
    procs_file = None

    @staticmethod
    def open(*args, **kwargs):
        assert (len(args) > 0 or len(kwargs) > 0)

        procs_dict = {}
        if Driver.procs_file is not None:
            with open(Driver.procs_file, "rb") as f:
                procs_file_content = f.read().decode()

            procs_xml = ElementTree.fromstring(procs_file_content)

            procs = procs_xml.findall("Procedure")
            for proc in procs:
                name = proc.attrib["name"]
                content = proc.text
                queries = content.split(";")
                actual_queries = []
                for query in queries:
                    query = query.strip()
                    if query != "":
                        actual_queries.append(query)
                procs_dict[name] = actual_queries

        if Driver.conn_string is None:
            raise RuntimeError("In order to use the test Driver a connection string must be set in the class")

        return Connection(
            conn_string=Driver.conn_string,
            procs_dict=procs_dict,
        )
