package be.iminds.ilabt.jfed.lowlevel.user;

import be.iminds.ilabt.jfed.fedmon.webapi.service.json.Server;
import be.iminds.ilabt.jfed.lowlevel.authority.AuthorityFinder;
import be.iminds.ilabt.jfed.util.GeniUrn;
import be.iminds.ilabt.jfed.util.IOUtils;
import com.google.common.base.Charsets;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;

/**
 * User: twalcari
 * Date: 7/14/2016
 * Time: 16:21
 */
public class KeyCertUrlUserLoginInfo extends AbstractUserLoginInfo {

    private final URL url;

    KeyCertUrlUserLoginInfo(URL url, GeniUserFactory geniUserFactory, AuthorityFinder authorityFinder) throws IOException {
        super(url != null ? IOUtils.urlToString(url, Charsets.UTF_8) : null, geniUserFactory, authorityFinder);
        this.url = url;

        checkForErrors();
    }

    KeyCertUrlUserLoginInfo(URL url, GeniUrn userUrn, Server userAuthority, GeniUserFactory geniUserFactory) throws IOException {
        super(url != null ? IOUtils.urlToString(url, Charsets.UTF_8) : null, userUrn, userAuthority, geniUserFactory);
        this.url = url;

        checkForErrors();
    }

    private void checkForErrors() {
        if (url != null && keyCertContent == null)
            addError("Could not read key-certificate-pair from url");
    }


    @Override
    public String getUserLoginTypeName() {
        return "Login Certificate Url";
    }

    @Override
    public boolean equals(UserLoginInfo o) {
        if (!(o instanceof KeyCertUrlUserLoginInfo))
            return false;

        if (!Objects.equals(url, ((KeyCertUrlUserLoginInfo) o).url))
            return false;

        return super.equalInfo(o);
    }

    public URL getUrl() {
        return url;
    }


}
