"""Pure ordering of the existing static Home items; no plugin call on Home."""
import json
import xml.etree.ElementTree as ET

SETTING = 'skin_menu_order'


def normalize(value, known):
    if isinstance(value, str):
        try:
            value = json.loads(value)
        except ValueError:
            value = []
    result = []
    for item in (value if isinstance(value, list) else []) + list(known):
        if isinstance(item, str) and item in known and item not in result:
            result.append(item)
    return result


def content(root):
    return root.find(".//control[@id='9000']/content")


def reorder(data, order):
    root = ET.fromstring(data, parser=ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
    listing = content(root)
    items = {item.findtext("property[@name='id']"): item for item in listing.findall('item')}
    wanted = normalize(order, items)
    if wanted == list(items):
        return data
    for item in items.values():
        listing.remove(item)
    listing.extend(items[key] for key in wanted)
    return ET.tostring(root, encoding='utf-8', xml_declaration=True)
