#! /usr/bin/python
# -*- coding: utf-8 -*-
import xml.sax
import logging
logger = logging.getLogger(__name__)


class GlmcSaxHandler(xml.sax.ContentHandler):
    def __init__(self):
        xml.sax.ContentHandler.__init__(self)
        logger.info('GLMC SAX handler init.')
        self.node = {}
        self.nodePara = {}
        self.lics = []
        self.lic = {}
        self.isLic = False

        self.alarm = {}
        self.is_alarm = False

        self.key = None

    def startElementNS(self, name, qname, attrs):
        self.startElement(name, attrs)

    def endElementNS(self, name, qname):
        self.endElement(name)

    def startElement(self, name, attrs):
        if 'lic' == name:
            self.isLic = True
            logger.info('Found a lic section.')
        if 'alarm' == name:
            self.is_alarm = True
            logger.info('Found the alarm information.')
        self.key = name

    def characters(self, content):
        if self.isLic:
            if 'lic' != self.key:
                if self.key is not None:
                    self.lic[self.key] = content
        elif self.is_alarm:
            if 'alarm' != self.key:
                if self.key is not None:
                    self.alarm[self.key] = content
        else:
            if 'node' != self.key:
                if self.key is not None:
                    self.nodePara[self.key] = content

    def endElement(self, name):
        if name == self.key:
            self.key = None
        if 'lic' == name:
            self.isLic = False
            self.lics.append(self.lic)
            self.lic = {}
        if 'alarm' == name:
            self.is_alarm = False

    def endDocument(self):
        self.node["nodePara"] = self.nodePara
        self.node["lics"] = self.lics
        self.node['alarm'] = self.alarm
        logger.info('End the parsing of XML.')


class GlmcNodeInfo:

    def __init__(self, xml_path):
        try:
            parser = xml.sax.make_parser()
            handler = GlmcSaxHandler()
            parser.setContentHandler(handler)
            parser.parse(open(xml_path, 'r'))
            self.node = handler.node
        except Exception as e:
            logger.critical('Failed to SAX the given file: %s, ERROR: %s' % (str(xml_path), str(e)))

    def get_node_info(self):
        return self.node


# g = GlmcNodeInfo('/Users/lowitty/proj/pycharm/zacademy/config/ssh_daemon/gmlc/gmlc_node_test.xml')
# print g.get_node_info()