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

import be.iminds.ilabt.jfed.fedmon.webapi.service.json.Server;
import be.iminds.ilabt.jfed.lowlevel.GeniUser;
import be.iminds.ilabt.jfed.lowlevel.authority.AuthorityFinder;
import be.iminds.ilabt.jfed.lowlevel.userloginmodel.InvalidLoginException;
import be.iminds.ilabt.jfed.util.GeniUrn;
import be.iminds.ilabt.jfed.util.IOUtils;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * User: twalcari
 * Date: 7/14/2016
 * Time: 15:24
 */
public class KeyCertFileUserLoginInfo extends AbstractUserLoginInfo {

    private final File keyCertFile;

    KeyCertFileUserLoginInfo(File keyCertFile, GeniUserFactory geniUserFactory, AuthorityFinder authorityFinder) throws IOException {
        super(keyCertFile != null ? IOUtils.fileToString(keyCertFile) : null, geniUserFactory, authorityFinder);
        this.keyCertFile = keyCertFile;

        checkForErrors();
    }

    public KeyCertFileUserLoginInfo(File keyCertFile, GeniUrn userUrn, Server userAuthority, GeniUserFactory geniUserFactory) throws IOException {
        super(keyCertFile != null ? IOUtils.fileToString(keyCertFile) : null, userUrn, userAuthority, geniUserFactory);
        this.keyCertFile = keyCertFile;

        checkForErrors();
    }

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

    @Override
    public GeniUser login(char[] password) throws InvalidLoginException {
        return geniUserFactory.createGeniUser(keyCertFile, password);
    }

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

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

        if(!Objects.equals(keyCertFile, ((KeyCertFileUserLoginInfo) o).keyCertFile))
            return false;

        return super.equalInfo(o);
    }

    public File getFile() {
        return keyCertFile;
    }
}
