package com.agilex.healthcare.schedulingmanager.security;

import com.agilex.healthcare.mobilehealthplatform.security.Roles;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;


public class StaffUserDisclaimerVoter<S> implements AccessDecisionVoter<S> {

	@Override
	public boolean supports(ConfigAttribute attribute) {
        return "CHECK_STAFF_USER_DISCLAIMER".equals(attribute.getAttribute());
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

	
	//Deny or abstain, do not Grant
	@Override
	public int vote(Authentication authentication, S s,
			Collection<ConfigAttribute> attributes) {

        for (ConfigAttribute attribute : attributes) {

            if (supports(attribute)){
                if (hasRole(authentication.getAuthorities(), Roles.ROLE_STAFF)){
                	// TODO: VOTER IS CURRENTLY TURNED OFF.  TURN BACK ON WHEN OTHER PROVIDER APPS IMPLEMENT SUD
                	//int sudVote = voteOnSud(s, authentication);
                    //return sudVote;
                	return AccessDecisionVoter.ACCESS_GRANTED;
                }
                else{
                    return AccessDecisionVoter.ACCESS_ABSTAIN;
                }
            }
        }
        return AccessDecisionVoter.ACCESS_ABSTAIN;
	}

    private boolean hasRole(Collection<? extends GrantedAuthority> authorities, String role) {
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals(role)) {
                return true;
            }
        }
        return false;
    }
 
}
