#! /usr/bin/python
import xml.dom.minidom

doc = xml.dom.minidom.Document()

def caps_to_elements (all_elements):
    elements = []
    for element in all_elements.split('element-'):
        if not element.strip ():
            continue
        all_caps = element.split(';')
        element_name = all_caps[0].strip()
        all_caps = all_caps[1:]
        decoders, urisrcs = [], []
        for caps in all_caps:
            caps = caps.strip()
            if 'decoder-' in caps:
                decoders.append(caps[8:])
            if 'urisource-' in caps:
                urisrcs.append(caps[10:])
        elements.append((element_name, decoders, urisrcs))
    return elements

def add_attribute (element, name, value):
    attr = doc.createAttribute (name)
    element.setAttributeNode (attr)
    element.setAttribute(name, str(value))

def add_element_with_text (element, name, text):
    new_elem = doc.createElement (name)
    text_elem = doc.createTextNode (str(text))
    new_elem.appendChild (text_elem)
    element.appendChild (new_elem)

def merge_yaml_files(file1, file2):
    import yaml, xmlrpclib
    if file1 == '--': 
      yaml_dic_1 = yaml.load(sys.stdin)
    else:
      yaml_dic_1 = yaml.load(open(file1))
    yaml_dic_2 = yaml.load(open(file2))
    yaml_dic_merged = {'products': []}
    for product_1 in yaml_dic_1['products']:
        if yaml_dic_2.has_key ('products'):
          for product_2 in yaml_dic_2['products']:
            if product_2['name'] == product_1['name']:
              product_merge = {}
              for key in product_1:
                product_merge[key] = product_1[key]
              for key in product_2:
                product_merge[key] = product_2[key]
              yaml_dic_merged['products'] += [product_merge]
        else:
            yaml_dic_merged['products'] += [product_1]
    for key in 'url', 'id', 'logo', 'flavor-distro', 'flavor-distro-version':
      if   key  in yaml_dic_1: yaml_dic_merged[key] = yaml_dic_1[key]
      elif key  in yaml_dic_2: yaml_dic_merged[key] = yaml_dic_2[key]
      #else: print "could not find %s" % key
    return yaml_dic_merged

def get_elements_from_caps (caps):
    elements = []
    for item in caps[0].split(';'):
        if 'element-' in item:
            elements.append(item[8:])
    return elements

def create_element (element):
    elemElem = doc.createElement ('element')
    add_attribute (elemElem, 'name', element[0])
    if element[1]:
        for decoder in element[1]:
            add_element_with_text (elemElem, 'decoder', decoder)
    if element[2]:
        for urisrc in element[2]:
            add_element_with_text (elemElem, 'urisource', urisrc)
    return elemElem

def create_plugin (plugin):
    plugElem = doc.createElement ('plugin')
    add_attribute (plugElem, 'name', plugin['name'])
    add_attribute (plugElem, 'version', plugin['version'])
    add_attribute (plugElem, 'description', plugin['description'])
    add_attribute (plugElem, 'origin', plugin['origin'])
    if plugin['caps']:
        for caps in plugin['caps']:
            for element in caps_to_elements (caps):
                plugElem.appendChild ( create_element (element))
    return plugElem

def create_flavor (arch, name, version, flavors):
    flavor = doc.createElement ('flavor')
    uri = '-'.join(["http://shop.fluendo.com/pub/fluendo", name])
    uri += '-'+'.'.join([str(version), arch, 'tar', 'bz2'])
    add_attribute (flavor, 'arch', arch)
    add_attribute (flavor, 'comment', ' ')
    add_attribute (flavor, 'base-req', '0.10.0')
    add_attribute (flavor, 'core-req', '0.10.0')
    add_attribute (flavor, 'last-modified', '2008-02-20')
    add_attribute (flavor, 'system', 'Linux')
    if flavors[0]:
        add_attribute (flavor, 'distro', flavors[0])
    else:
        add_attribute (flavor, 'distro', 'generic')
    if flavors[1]:
        add_attribute (flavor, 'distro-version', flavors[1])
    else:
        add_attribute (flavor, 'distro-version', 'any')
    add_attribute (flavor, 'uri', uri)
    return flavor

def create_product (dic, id, flavor):
    product = doc.createElement ('product')
    if 'id' not in dic: dic['id'] = id
    if 'rank' not in dic: dic['rank'] = 0
    if 'price' not in dic: dic['price'] = "0.00"
    if 'description' not in dic: dic['description'] = dic['name']
    if 'summary' not in dic:
        if dic.has_key('plugins') and dic['plugins'] and len(dic['plugins']) == 1:
            if dic['plugins'][0].has_key ('description') and dic['plugins'][0]['description']:
                dic['summary'] = dic['plugins'][0]['description']
            else:
                dic['summary'] = "Missing Summary"
        else:
            dic['summary'] = "Missing Summary"
    add_attribute (product, 'id', str(dic['id']))
    add_attribute (product, 'nick', dic['name'])
    add_attribute (product, 'version', dic['version'])
    add_attribute (product, 'rank', dic['rank'])
    add_attribute (product, 'price', dic['price'])
    add_attribute (product, 'logo-uri', 'http://download.fluendo.com/images/windowsmedia.png')
    if dic.has_key ('plugins') and dic['plugins']:
        for plugin in dic['plugins']:
            product.appendChild (create_plugin (plugin))
    add_element_with_text (product, 'name', dic['description'])
    add_element_with_text (product, 'summary', dic['summary'])
    if dic.has_key ('architectures') and dic['architectures']:
        for architecture in dic['architectures']:
            product.appendChild (create_flavor (architecture, dic['name'], dic['version'], flavor))
    return product

def get_from_dic_safe (dic, key):
    if dic.has_key (key):
        return dic[key]
    return None

if __name__ == '__main__':
    import sys, os
    import yaml
    if len(sys.argv) == 1:
        print "%s <yaml_file1> [yaml_file2]" % sys.argv[0]
        sys.exit(1)
    if len(sys.argv) == 3:
        merged_dic = merge_yaml_files(sys.argv[1], sys.argv[2])
    else:
        merged_dic = yaml.load(open(sys.argv[1]))

    root = doc.createElement ('products')
    doc.appendChild (root)
    # Add product url and id
    for key in 'url', 'id', 'logo':
        if merged_dic.has_key (key):
            add_attribute (root, key, merged_dic[key])
    id = 0
    # Check for the flavor-distro and version
    flavor = [get_from_dic_safe (merged_dic, 'flavor-distro'), get_from_dic_safe (merged_dic, 'flavor-distro-version')]
    for product in merged_dic['products']:
        root.appendChild (create_product (product, id, flavor)); id += 1
    try:
        doc.writexml(sys.stdout, newl="\n", addindent="\t")
    except AttributeError:
        # Fallback for Python < 2.4
        import xml.dom.ext
        xml.dom.ext.PrettyPrint(doc)
