'''
Created on 

@author: haoweizh
'''
from bs4 import BeautifulSoup
from bs4 import NavigableString
from bs4 import Tag 
from bs4 import PageElement
import copy



soup2 = BeautifulSoup(open("mgw.xml"), "xml")
first_link = soup2.ipv4____interface
tag = soup2.find_all("h248-config")
#print(tag)
#print(type(first_link.name))  "h248-config"
#first_link2 =first_link.find_next_siblings("ipv4____interface")
#first_link3 =first_link.find_next_sibling("ipv4____interface")
#first_link4 =soup2.find_all_next("ipv4____interface")
#a = soup2.select("ip > ipv4____interface")
#b = soup2.ip
#print(b.prettify())
#print('&' * 50)
#b.unwrap()
#print(b.prettify())
#a_tag = soup2.ip.extract()
#print(soup2)
#print('&' * 50)
#print(a_tag.prettify())
#print(a_tag.name)
##ip_tag = a_tag.unwrap()
#print(ip_tag)
#print(b.prettify())
#print(first_link)
#print(a)
#print(first_link2)
#print(first_link4)
#print(soup.name)
#syst = soup.test
#print(soup.ip.prettify())
#print(syst.string)

#print(len(list(soup.config.children)))
#print('*' * 20)
#print(soup.ip.parent)
class netconfsoi:
    modNameList = ('syslog', 'ip', 'alarm', 'ip-flooding', 'arp-flooding', 'ipv4-filter', 'ipng-firewall', 'ip-realm', 'h248', 'datapath-check', 'capacity-profile', 'profilecfg', 'snmp', 'ntp', 'next-hop-ip-monitor', 'vqt', 'rmgr' )
    addMediaidList = ('h248-vmg',)
    #changeNameList = (('h248-config', 'h248-parameters'),('mg-config', 'mg-parameters'))
    oldName =('h248-config','mg-config')
    newName = ('h248-parameters', 'mg-parameters')
    media_tag = 'media-plane-id'
    
    def __init__(self, file, format):
        self.soup = BeautifulSoup(open(file), format)
        #print(self.soup.prettify())
        self.loopReplaceSpeCh(self.soup)
        self.mediaid = self.getSingleNode(self.media_tag)
    def loopReplaceSpeCh(self, node, old = '-', new = '____'):
        for child in node.children:
            if(isinstance(child,Tag)):
                child.name = child.name.replace(old, new)
                # print(child.name)
                self.loopReplaceSpeCh(child, old, new)
                
                
    def replaceSingalSpeCh(self, name):
        return name.replace('-', '____')

    def getSingleNode(self, arg):
        arg = self.replaceSingalSpeCh(arg)
        tag = self.soup.find(arg)
        return tag

    def contain2list(self, nodeName):
        childlist = {}
        curNodeList = []
        handleNode = self.getSingleNode(nodeName)
        #parentNode = self.soup.ip.parent
        #treenode = self.soup.ip.extract()
        parentNode = handleNode.parent
        treenode = handleNode.extract()
        
        for child in treenode.children:
            if child is not None and isinstance(child, Tag):
                if childlist.get(child.name) is None:
                    childlist[child.name] = [child]
                else:
                    childlist[child.name].append(child)
        treenode.clear()
        for i in range(len(childlist)):
            curNodeList.append(self.cloneMediaId(treenode) )
        for ty in childlist.values():
            curNode = curNodeList.pop()
            curNode.append(copy.copy(self.cloneMediaId(self.mediaid)))
            #print(curNode)
            for chn in ty:
                curNode.append(chn)
            parentNode.append(curNode)
    
    def contain2listforall(self):
        for node in self.modNameList:
            if self.getSingleNode(node) is None:
                continue
            else:
                self.contain2list(node)
                
    def addMediaId(self, node = None):
        if node is None:
            for nodeName in self.addMediaidList:
                if self.getSingleNode(nodeName) is None:
                    continue
                else:
                    self.getSingleNode(nodeName).insert(0, self.cloneMediaId(self.mediaid))
        else:
            node.append()
     
    def modifyTagName(self, oldName, newName):
        nameList = self.soup.find_all(self.replaceSingalSpeCh(oldName))
        for node in nameList:
            node.name = newName
     
    def modifyTagNameAll(self, func,  *seqs):
        for args in zip(*seqs):
            func(*args)
        
    def doIt(self):
        self.modifyTagNameAll(self.modifyTagName, self.oldName, self.newName)
                       
    def cloneMediaId(self, tag):
        return copy.copy(tag)
    
    
soiobject = netconfsoi("mgw.xml", "xml")

#soiobject.loopReplaceSpeCh(soiobject.soup)
#print(soiobject.mediaid)
#print(soup.prettify())

soiobject.contain2listforall()
soiobject.addMediaId()
soiobject.doIt()
#print(soiobject.soup.prettify())
#soiobject.contain2list('system-name')
soiobject.loopReplaceSpeCh(soiobject.soup, '____', '-')
print(soiobject.soup.prettify())
#print(soup.prettify())
######################################################################################################
#  syslog ip alarm ip ip-flooding arp-flooding ipv4-filter ipng-firewall ip-realm h248 datapath-check 
#  capacity-profile profilecfg snmp ntp next-hop-ip-monitor vqt rmgr 
#######################################################################################################