package org.xbib.io.webdav.common;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xbib.io.webdav.api.Namespace;
import org.xbib.io.webdav.api.XMLizable;

/**
 * <code>Filter</code>...
 */
public class Filter implements XMLizable {

    private final String filterName;
    private final Namespace filterNamespace;
    private final String filterValue;

    public Filter(String filterName, Namespace filterNamespace, String filterValue) {
        if (filterName == null) {
            throw new IllegalArgumentException("filterName must not be null.");
        }
        this.filterName = filterName;
        this.filterNamespace = filterNamespace;
        this.filterValue = filterValue;
    }

    public Filter(Element filterElem) {
        filterName = filterElem.getLocalName();
        filterNamespace = DomUtil.getNamespace(filterElem);
        filterValue = DomUtil.getTextTrim(filterElem);
    }

    public String getName() {
        return filterName;
    }

    public Namespace getNamespace() {
        return filterNamespace;
    }

    public String getValue() {
        return filterValue;
    }

    public boolean isMatchingFilter(String localName, Namespace namespace) {
        boolean matchingNsp = (filterNamespace == null) ? namespace == null : filterNamespace.equals(namespace);
        return filterName.equals(localName) && matchingNsp;
    }

    public Element toXml(Document document) {
        return DomUtil.createElement(document, filterName, filterNamespace, filterValue);
    }

}