package cz.muni.fi.lasaris.sbms.api.auth;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.container.ContainerRequestContext;

import cz.muni.fi.lasaris.sbms.SBMSApplication;

public class PropertiesAuthProvider implements AuthProvider {
	
	Map<String,String> passwords;
	Map<String, String> roles;
	
	public PropertiesAuthProvider() {
		this.passwords = new HashMap<String, String>();
		this.roles = new HashMap<String, String>();
		
		String usersProp = SBMSApplication.getInstance().getSBMSProperties().getProperty("api.customAuth.users");
		String roleUProp = SBMSApplication.getInstance().getSBMSProperties().getProperty("api.customAuth.roles.user");
		String roleAProp = SBMSApplication.getInstance().getSBMSProperties().getProperty("api.customAuth.roles.admin");
		
		if(usersProp != null) {
			String[] ups = usersProp.split("\\|");
			for(int i = 0; i < ups.length; i++) {
				String[] u = ups[i].split(":");
				this.passwords.put(u[0],u[1]);
			}
		}
		
		if(roleUProp != null) {
			String[] rps = roleUProp.split("\\|");
			for(int i = 0; i < rps.length; i++) {		
				this.roles.put(rps[i],"user");
			}
		}
		
		if(roleAProp != null) {
			String[] rps = roleAProp.split("\\|");
			for(int i = 0; i < rps.length; i++) {		
				this.roles.put(rps[i],"admin");
			}
			
		}
		
	}
	
	@Override
	public boolean authenticate(String user, String password, ContainerRequestContext requestContext) {
		return passwords.containsKey(user) && passwords.get(user).equals(password);
	}

	@Override
	public boolean authorize(String user, String role, ContainerRequestContext requestContext) {
		return roles.containsKey("user") && roles.get(user).equals(role);
	}

}
