"use strict";
/**
 * Copyright (c) Haiku 2016-2018. All rights reserved.
 */
Object.defineProperty(exports, "__esModule", { value: true });
var assignClass_1 = require("./assignClass");
var assignStyle_1 = require("./assignStyle");
var STYLE = 'style';
var OBJECT = 'object';
var CLASS = 'class';
var CLASS_NAME = 'className';
var NS = 'http://www.w3.org/1999/xlink';
var XLINK_HREF = 'xlink:href';
var setAttribute = function (domElement, virtualElement, key, val) {
    if (key === XLINK_HREF) {
        var p0 = domElement.getAttributeNS(NS, key);
        if (p0 !== val) {
            domElement.setAttributeNS(NS, key, val);
        }
    }
    else {
        var p1 = domElement.getAttribute(key);
        if (p1 !== val) {
            domElement.setAttribute(key, val);
        }
    }
};
function assignAttributes(domElement, virtualElement, component, isPatchOperation) {
    if (!isPatchOperation) {
        // Remove any attributes from the previous run that aren't present this time around
        if (domElement.haiku && domElement.haiku.element) {
            for (var oldKey in domElement.haiku.element.attributes) {
                var oldValue = domElement.haiku.element.attributes[oldKey];
                var newValue = virtualElement.attributes[oldKey];
                if (oldKey !== STYLE) {
                    // Removal of old styles is handled downstream; see assignStyle()
                    if (newValue === null || newValue === undefined || oldValue !== newValue) {
                        domElement.removeAttribute(oldKey);
                    }
                }
            }
        }
    }
    for (var key in virtualElement.attributes) {
        var anotherNewValue = virtualElement.attributes[key];
        if (key === STYLE &&
            anotherNewValue &&
            typeof anotherNewValue === OBJECT) {
            if (Object.keys(anotherNewValue).length > 0) {
                assignStyle_1.default(domElement, anotherNewValue, component, isPatchOperation);
            }
            continue;
        }
        if ((key === CLASS || key === CLASS_NAME) && anotherNewValue) {
            assignClass_1.default(domElement, anotherNewValue);
            continue;
        }
        setAttribute(domElement, virtualElement, key, anotherNewValue);
    }
    return domElement;
}
exports.default = assignAttributes;
//# sourceMappingURL=assignAttributes.js.map