from lxml import etree
from lxml import objectify

class Config:
    def __init__(self):
        self.tree = None
        self.fname = None


    def new(self, fname=None):
        E = objectify.E
        self.root = E.psqlconsole(
            E.servers,
            E.editor(
                E.nodes(
                    E.node('-- Type your query here', name='Untitled', type='text'),
                    selected='Untitled'
                )
            ),
            E.window(
                E.size(
                    E.width(800),
                    E.height(600)
                ),
                E.dividers(
                    E.verticaldivider(300),
                    E.horizontaldivider(500),
                    E.editordivider(-1)
                )
            )
        )
        self.tree = etree.ElementTree(self.root)
        self.servers = self.root.servers
        self.fname = fname


    def load(self, fname=None):
        if fname:
            self.fname = fname
        self.tree = objectify.parse(self.fname)
        self.root = self.tree.getroot()
        self.servers = self.root.servers


    def save(self, fname=None):
        if fname:
            self.fname = fname
        self.tree.write(
            self.fname,
            encoding='utf-8',
            xml_declaration=True,
            pretty_print=True,
            compression=6)


    def add_server(self, name, host, port, user, password):
        e = etree.SubElement(self.servers, 'server')
        e.name = name
        e.host = host
        e.port = port
        e.user = user
        e.password = password
        return e


cfg = Config()


if __name__ == '__main__':
    cfg.load('../psqlconsole.xml.gz')
    print(cfg.root.servers.server[0].host.text)
    cfg.save()

