package gov.va.med.edp.springframework.security.providers.vistalink;

import gov.va.med.edp.springframework.security.userdetails.VistaUserDetails;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.util.StringUtils;

public class VistaAuthenticationToken extends UsernamePasswordAuthenticationToken {

    static final String UNAUTHENTICATED = "UNAUTHENTICATED";
    private static final String SEP = ";";

    private String accessCode;
    private String verifyCode;

    public VistaAuthenticationToken(String stationNumber, String accessCode, String verifyCode, String remoteAddress) {
        super(UNAUTHENTICATED + "@" + stationNumber, (StringUtils.hasLength(accessCode) && StringUtils.hasLength(verifyCode) && StringUtils.hasLength(remoteAddress) ? accessCode + SEP + verifyCode + SEP + remoteAddress : null));
        this.accessCode = StringUtils.hasLength(accessCode) ? accessCode : null;
        this.verifyCode = StringUtils.hasLength(verifyCode) ? verifyCode : null;
        super.setDetails(StringUtils.hasLength(remoteAddress) ? remoteAddress : null);
    }

    public VistaAuthenticationToken(VistaUserDetails user, String accessCode, String verifyCode, String remoteAddress, GrantedAuthority[] authorities) {
        super(user, (StringUtils.hasLength(accessCode) && StringUtils.hasLength(verifyCode) && StringUtils.hasLength(remoteAddress) ? accessCode + SEP + verifyCode + SEP + remoteAddress : null), authorities);
        this.accessCode = StringUtils.hasLength(accessCode) ? accessCode : null;
        this.verifyCode = StringUtils.hasLength(verifyCode) ? verifyCode : null;
        super.setDetails(StringUtils.hasLength(remoteAddress) ? remoteAddress : null);
    }

    public VistaUserDetails getVistaUserDetails() {
        if (isAuthenticated())
            return (VistaUserDetails) getPrincipal();
        return null;
    }

    public String getDuz() {
        if (isAuthenticated())
            return getVistaUserDetails().getDuz();
        return null;
    }

    public String getStationNumber() {
        if (isAuthenticated())
            return getVistaUserDetails().getLoginStationNumber();
        else
            return ((String) getPrincipal()).substring(((String) getPrincipal()).lastIndexOf("@") + 1);
    }

    public String getAccessCode() {
        return accessCode;
    }

    public String getVerifyCode() {
        return verifyCode;
    }

    public String getRemoteAddress() {
        return (String) getDetails();
    }

    public void setDetails(Object details) {
        // NOOP
    }
}
