import lxml.etree as ET
import random
import time


def newValues(serviceCode, serviceVersion, serviceInputParameter, serviceInput, flatElements, nestedElements):
    with open('template.xml') as f:
        tree = ET.parse(f)
        root = tree.getroot()

    for elem in root.getiterator():
        try:
            elem.text = elem.text.replace('changeServiceCode', serviceCode)
            elem.tag = elem.tag.replace('{http://x-road.eu/xsd/connector/test11/v1}changeServiceCode', '{http://x-road.eu/xsd/connector/'+serviceCode+'/'+serviceVersion+'}'+serviceCode)

            elem.text = elem.text.replace('changeServiceVersion', serviceVersion)
            elem.tag = elem.tag.replace('changeServiceVersion', serviceVersion)

            elem.tag = elem.tag.replace('changeInputParameter', serviceInputParameter)

            elem.text = elem.text.replace('changeInput', serviceInput)

            elem.text = elem.text.replace('requestid', str(int(time.time())))

        except AttributeError:
            pass

    if flatElements > 0:
        for i in range(flatElements):
            root[1][0][0].addnext(ET.XML("<nr>"+''.join(random.choice("ABCDEFGHIJKLMNOPQRSTUVWXY") for x in range(6))+"</nr>"))
        root[1][0].remove(root[1][0][0])

    if nestedElements > 0:
        for i in range(nestedElements):
            root[1][0].insert(root[1][0].index(root[1][0][0])+1, ET.XML("<layer1> <layer2><core>"+''.join(random.choice("ABCDEFGHIJKLMNOPQRSTUVWXY") for x in range(6))+"</core></layer2></layer1>"))
        root[1][0].remove(root[1][0][0])

    tree.write('TestJMX/out.xml')
