from System import DateTime
from datetime import datetime
from System import String
from System.Text import Encoding
from System.Text import StringBuilder

import clr
clr.AddReference("System.Xml")
from System.Xml import XmlDocument
from System.Xml import XmlWriter
from System.Xml import XmlWriterSettings

xml_date_format = "%Y-%m-%dT%H:%M:%S.%fZ"

def convertString2X(value, type):
    if not value:
        return None
    conDict = {
    "Edm.String": lambda x: str(value),
    "Edm.Double": lambda x: float(value),
    "Edm.DateTime": lambda x: DateTime.Parse(value)
    #"Edm.DateTime": lambda x: datetime.strptime(value[:-2]+'Z', xml_date_format)
    }
    return conDict[type](value) if conDict.has_key(type) else str(value)

def xml2dict(xml):
    entities = []
    doc = XmlDocument()
    doc.LoadXml(xml)
    properties = doc.GetElementsByTagName("m:properties")
    for property in properties:
        entity = {}
        entities.append(entity)
        for column in property.ChildNodes:
            if (column.Attributes.Count>0):
                attr = column.Attributes["m:type"]
                entity[column.LocalName] = convertString2X(column.InnerText, attr.Value) if attr and attr !="" else convertString2X(column.InnerText, "Edm.String")
            else:
                entity[column.LocalName] = convertString2X(column.InnerText, "Edm.String")
    return entities

def dict2xml(record):
    defaultNameSpace = "http://www.w3.org/2005/Atom";
    dataservicesNameSpace = "http://schemas.microsoft.com/ado/2007/08/dataservices";
    metadataNameSpace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

    xmlWriterSettings = XmlWriterSettings()
    xmlWriterSettings.OmitXmlDeclaration = False;
    xmlWriterSettings.Encoding = Encoding.UTF8;

    entry = StringBuilder()
    xmlWriter = XmlWriter.Create(entry)
    xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
    xmlWriter.WriteWhitespace("\n");
    xmlWriter.WriteStartElement("entry", defaultNameSpace);
    xmlWriter.WriteAttributeString("xmlns", "d", None, dataservicesNameSpace);
    xmlWriter.WriteAttributeString("xmlns", "m", None, metadataNameSpace);
    xmlWriter.WriteElementString("title", None);
    xmlWriter.WriteElementString("updated", String.Format("{0:o}", DateTime.UtcNow));
    xmlWriter.WriteStartElement("author");
    xmlWriter.WriteElementString("name", None);
    xmlWriter.WriteEndElement();
    xmlWriter.WriteElementString("id", None);
    xmlWriter.WriteStartElement("content");
    xmlWriter.WriteAttributeString("type", "application/xml");
    xmlWriter.WriteStartElement("properties", metadataNameSpace);

    for key, val in record.iteritems():
        xmlWriter.WriteStartElement(key, dataservicesNameSpace);
        if isinstance(val, float):
            xmlWriter.WriteAttributeString("type", metadataNameSpace, "Edm.Double")
        elif isinstance(val, datetime):
            xmlWriter.WriteAttributeString("type", metadataNameSpace, "Edm.DateTime")
        xmlWriter.WriteString(str(val))
        xmlWriter.WriteEndElement()

    xmlWriter.WriteEndElement();
    xmlWriter.WriteEndElement();
    xmlWriter.WriteEndElement();
    xmlWriter.Close();

    requestContent = entry.ToString();
    return requestContent;


