namespace eval comanche::serialize {
}

proc comanche::serialize::xuiObj2XML {xuiObject domnode} {
    switch [$xuiObject getXuiClass] {
        number - string - choice - boolean {
            return [simpleXuiObj2XML $xuiObject $domnode]
        } list {
            return [xuiList2XML $xuiObject $domnode]
        } structure {
            return [xuiStructure2XML $xuiObject $domnode]
        } alternate {
            return [xuiAlternate2XML $xuiObject $domnode]
        }
    }
}

proc comanche::serialize::simpleXuiObj2XML {xuiObject domnode} {
    switch [$xuiObject getXuiClass] {
        number - string - choice - boolean {
	    set element [dom::document createElement $domnode [$xuiObject getName]]
   	    dom::document createTextNode $element [$xuiObject getValue]
	    return $element
        } default {
            error "Tried to serialize object of type [$xuiObject getXuiClass] with simple method."
        }
    } 
}

proc comanche::serialize::xuiList2XML {xuiList domnode} {
    set result {}
    set element [dom::document createElement $domnode [$xuiList getName]]
    foreach child [$xuiList getChildren] {
        comanche::serialize::xuiObj2XML $child $element
    }
    return $element
}

proc comanche::serialize::xuiStructure2XML {xuiStructure domnode} {
    set element [dom::document createElement $domnode [$xuiStructure getName]]
    foreach structureElement [$xuiStructure getComponents] {
        comanche::serialize::xuiObj2XML $structureElement $element
    }
    return $element
}

proc comanche::serialize::xuiAlternate2XML {xuiAlternate domnode} {
   set result {}
   set element [$xuiAlternate getSelectedComponent]
   return [list [$element getName] [xuiObj2XML $element $domnode]]
}

proc comanche::serialize::getXmlTextFromXui {xuiObject} {
    set doc [dom::newDoc]
    set dom [comanche::serialize::xuiObj2XML $xuiObject $doc]
    set xmlDoc [dom::DOMImplementation serialize $dom]
    dom::deleteDoc $doc 
    return $xmlDoc
}