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

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

public class PropertiesAuthProvider implements AuthProvider {
	
	Map<String,String> passwords;
	Map<String, String> roles;
	
	public PropertiesAuthProvider() {
		
	}
	
	public boolean authenticate(String user, String password) {
		return passwords.containsKey(user) && passwords.get(user).equals(password);
	}

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

	public void init(Properties props) {
		this.passwords = new HashMap<String, String>();
		this.roles = new HashMap<String, String>();
		
		String usersProp = props.getProperty("auth.propertiesAuth.users");
		String roleUProp = props.getProperty("auth.propertiesAuth.roles.user");
		String roleAProp = props.getProperty("auth.propertiesAuth.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");
			}
			
		}
		
	}

}
