import xml.etree.ElementTree as ET
import numpy as np

FILENAME = '..\\info\\cfgklas.xml'

def parse(filename):

    def walk(root):
        if len(root) == 0:
            return
        else:
            for child in root:
                if child.tag == 'T':
                    samples[child.attrib['Name']] = []

                elif child.tag == 'V':
                    feature_arr = [int(v)/1000.0 for v in child.text.split(';')]
                    samples[root.attrib['Name']].append((child.attrib["ID"], feature_arr))
                elif child.tag == 'P':
                    features[child.attrib['Name']] = int(child.attrib['Index'])
                       # (int(child.attrib['Index']), int(child.attrib['Vaha'])/1000.0)

                walk(child)

    #key - class name, value - feature arrays
    samples = dict()
    #key - feature name, value - (index, weight)
    features = dict()

    tree = ET.parse(filename)
    root = tree.getroot()
    walk(root)

    return features, samples


def samples_to_Xy(samples):

    X, y = [], []
    for cl in samples:
        for sample in samples[cl]:
            X.append(sample[1])
            y.append(cl)
    return np.array(X), np.array(y)

def get_IDs(samples):
    ids = []
    for cl in samples:
        for sample in samples[cl]:
            ids.append(sample[0])
    return ids  

def assign_weights(features, X):
    _, weights = zip(*sorted(features.values(), key=lambda x: x[0]))
    return X * (np.array(weights) / 1000.0 )



# features, samples = parse(FILENAME)
