package org.gcube.keycloak.oidc.avatar.importer.libravatar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;

public class DNSUtil {

    protected static final Logger logger = LoggerFactory.getLogger(DNSUtil.class);

    protected final static String PLAIN_DNS_QUERY_TEMPLATE = "_avatars._tcp.%s";

    protected final static String SECURE_DNS_QUERY_TEMPLATE = "_avatars-sec._tcp.%s";

    public static String resolveSRVRecordFromEmail(String email) {
        return resolveSRVRecordFromEmail(PLAIN_DNS_QUERY_TEMPLATE, email);
    }

    public static String resolveSecureSRVRecordFromEmail(String email) {
        return resolveSRVRecordFromEmail(SECURE_DNS_QUERY_TEMPLATE, email);
    }

    protected static String resolveSRVRecordFromEmail(String queryTemplate, String email) {
        String[] emailTokens = email.toLowerCase().split("@");
        String domain = emailTokens[1];
        logger.trace("Email's domain is: {}", domain);
        return resolveSRVRecordForDomain(queryTemplate, domain);
    }

    protected static String resolveSRVRecordForDomain(String queryTemplate, String domain) {
        String query = String.format(queryTemplate, domain);
        logger.trace("Performing DNS query for domain: {}", query);
        try {
            Record[] records = new Lookup(query, Type.SRV).run();
            return records != null && records.length > 0 ? ((SRVRecord) records[0]).getTarget().toString() : null;
        } catch (TextParseException e) {
            logger.error("Performing the DNS query for SRV: " + query, e);
            return null;
        }
    }

}
