/* BdfServer_API - Copyright (c) 2021 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package fr.exemole.bdfserver.api.interaction;


/**
 *
 * @author Vincent Calame
 */
public final class Domain {

    private final String complete;
    private final String firstPart;
    private final String secondPart;

    public Domain(String firstPart, String secondPart) {
        if (firstPart == null) {
            throw new IllegalArgumentException("firstPart is null");
        }
        if (secondPart == null) {
            throw new IllegalArgumentException("secondPart is null");
        }
        this.firstPart = firstPart;
        this.secondPart = secondPart;
        this.complete = getCompleteDomain(firstPart, secondPart);
    }

    public String getFirstPart() {
        return firstPart;
    }

    public String getSecondPart() {
        return secondPart;
    }

    @Override
    public String toString() {
        return complete;
    }

    @Override
    public int hashCode() {
        return complete.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (getClass() != other.getClass()) {
            return false;
        }
        Domain otherDomain = (Domain) other;
        return otherDomain.complete.equals(this.complete);
    }

    public static String getCompleteDomain(String firstPart, String secondPart) {
        if (secondPart.isEmpty()) {
            return firstPart;
        }
        return firstPart + "-" + secondPart;
    }

    public static Domain parse(String complete) {
        int idx = complete.indexOf('-');
        if (idx == -1) {
            return new Domain(complete, "");
        } else {
            return new Domain(complete.substring(0, idx), complete.substring(idx + 1));
        }
    }

}
