package org.jivesoftware.smackx.ikey.element;

import org.jivesoftware.smack.packet.NamedElement;
import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.util.EqualsUtil;
import org.jivesoftware.smack.util.HashCode;
import org.jivesoftware.smack.util.Objects;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smack.util.XmlStringBuilder;

import java.net.URI;

public class SubordinateElement implements NamedElement {

    public static final String ELEMENT = "sub";
    public static final String ATTR_SUB_URI = "uri";
    public static final String ATTR_SUB_FINGERPRINT = "fpr";

    private final URI subUri;
    private final String subFingerprint;

    public SubordinateElement(URI subKeyItemUri, String subKeyFingerprint) {
        this.subUri = Objects.requireNonNull(subKeyItemUri, "uri MUST NOT be null nor empty.");
        this.subFingerprint = StringUtils.requireNotNullNorEmpty(subKeyFingerprint, "fpr MUST NOT be null nor empty.");
    }

    public URI getUri() {
        return subUri;
    }

    public String getFingerprint() {
        return subFingerprint;
    }

    @Override
    public String getElementName() {
        return ELEMENT;
    }

    @Override
    public XmlStringBuilder toXML(XmlEnvironment xmlEnvironment) {
        XmlStringBuilder xml = new XmlStringBuilder(this)
                .attribute(ATTR_SUB_URI, getUri().toString())
                .attribute(ATTR_SUB_FINGERPRINT, getFingerprint())
                .closeEmptyElement();
        return xml;
    }

    @Override
    public int hashCode() {
        return HashCode.builder()
                .append(getElementName())
                .append(getFingerprint())
                .append(getUri())
                .build();
    }

    @Override
    public boolean equals(Object other) {
        return EqualsUtil.equals(this, other, (e, o) -> e
                .append(getElementName(), o.getElementName())
                .append(getFingerprint(), o.getFingerprint())
                .append(getUri(), o.getUri()));
    }
}
