package de.fhg.iais.cortex.services.authentication;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import net.oauth.OAuth.Parameter;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;

import com.google.inject.Inject;
import com.google.inject.Provider;

import de.fhg.iais.cortex.services.authentication.types.Role;
import de.fhg.iais.cortex.services.authentication.types.Role.Profile;

public class SimpleOAuthService extends OAuthService {

    private Provider<Role> roleProvider = null;

    @Inject
    public SimpleOAuthService(IOAuthProvider oauthProvider, IOAuthValidator oauthValidator) {
        super(oauthProvider, oauthValidator);
    }

    @Override
    public String validateAccess(String method, String url, String authorizationHeader) throws OAuthException, IOException, URISyntaxException {

        List<Parameter> params = OAuthMessage.decodeAuthorization(authorizationHeader);

        OAuthMessage requestMessage = new OAuthMessage(method, url, params);

        OAuthConsumer consumer = this.provider.getConsumer(requestMessage);

        setCurrentRoleProfile(consumer);

        return consumer.consumerKey;
    }

    private void setCurrentRoleProfile(OAuthConsumer consumer) {

        Object profile = consumer.getProperty("profile");
        if ( profile == null ) {
            return;
        }

        if ( "full".equals(profile.toString().toLowerCase()) ) {
            this.roleProvider.get().setProfile(Profile.FULL);
        } else if ( "read".equals(profile.toString().toLowerCase()) ) {
            this.roleProvider.get().setProfile(Profile.READ);
        } else if ( "restricted_read".equals(profile.toString().toLowerCase()) ) {
            this.roleProvider.get().setProfile(Profile.RESTRICTED_READ);
        } else {
            this.roleProvider.get().setProfile(Profile.ANONYMOUS);
        }
    }

    @Inject
    public void setRoleProvider(Provider<Role> roleProvider) {
        this.roleProvider = roleProvider;
    }

}
