//  Created by Eric Marchand on 07/06/2017.
//  Copyright © 2017 Eric Marchand. All rights reserved.
//

import Foundation

extension MomAttribute: XMLObject {

    public init?(xml: XML?) {
        guard let xml = xml else { return nil }
        guard let element = xml.element,
                  element.name == "attribute" else {
            return nil
        }
        guard let name: String = element.attribute("name")
        else { return nil }
        let attributeType
        = AttributeType(rawValue: element.attribute("attributeType") ?? "undefined")
        ?? .undefined
        
        self.init(name: name, attributeType: attributeType)

        self.isOptional = element.attribute("optional")
        self.isDerived = element.attribute("derived")
        self.usesScalarValueType = element.attribute("usesScalarValueType")
        self.isIndexed = element.attribute("indexed")
        self.syncable = element.attribute("syncable")
        self.isTransient = element.attribute("transient")
        
        self.defaultValueString = element.attribute("defaultValueString")
        self.defaultDateTimeInterval = element.attribute("defaultDateTimeInterval")
        self.minValueString = element.attribute("minValueString")
        self.maxValueString = element.attribute("maxValueString")
        self.derivationExpression = element.attribute("derivationExpression")
        self.valueTransformerName = element.attribute("valueTransformerName")

        if let info = element.elements(forName: "userInfo").first,
           let uf = MomUserInfo(xml: info) {
            userInfo = uf
        }
    }

}
