package org.apache.slide.projector.processor.security;

import java.util.Map;

import org.apache.commons.contract.Context;
import org.apache.commons.contract.Information;
import org.apache.commons.contract.Processor;
import org.apache.commons.contract.Result;
import org.apache.commons.contract.constraints.StringConstraints;
import org.apache.commons.contract.descriptor.ParameterDescriptor;
import org.apache.commons.contract.descriptor.ResultDescriptor;
import org.apache.commons.contract.descriptor.StateDescriptor;
import org.apache.commons.contract.i18n.ParameterMessage;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.i18n.LocalizedError;
import org.apache.commons.i18n.LocalizedMessage;
import org.apache.slide.projector.Projector;
import org.apache.slide.projector.context.ProjectorContext;

/**
 * @version $Revision: 1.5 $
 */

public class Login implements Processor {
    private final static String USERNAME = "username";
    private final static String PASSWORD = "password";
    
    private final static String LOGIN_OK = "loginOk";
    private final static String LOGIN_FAILED = "loginFailed";
    public final static String ERRORS = "errors";

    private final static ParameterDescriptor[] parameterDescriptors = new ParameterDescriptor[] {
            new ParameterDescriptor(USERNAME, new ParameterMessage("login/user"), new StringConstraints(1,20)),
            new ParameterDescriptor(PASSWORD, new ParameterMessage("login/password"), new StringConstraints(4,12)),
        };
    private final static ResultDescriptor[] resultDescriptors = new ResultDescriptor[] {
            new ResultDescriptor(new StateDescriptor(LOGIN_OK, new LocalizedMessage("login/state/ok"))),
            new ResultDescriptor(new StateDescriptor(LOGIN_FAILED, new LocalizedMessage("login/state/failed")))
    };
    
    public Result process(Map parameter, Context context) throws Exception {
        String username = parameter.get(USERNAME).toString();
        String password = parameter.get(PASSWORD).toString();
        Credentials credentials = Projector.getRepository().login(username, password);
        if ( credentials == null ) {
            context.addInformation(new Information(Information.ERROR, new LocalizedError("login/invalidLogin"), new String[] { USERNAME, PASSWORD }));
            return new Result(LOGIN_FAILED);
        }
        ((ProjectorContext)context).setCredentials(credentials);
        return new Result(LOGIN_OK);
    }

    public ParameterDescriptor[] getParameterDescriptors() {
        return parameterDescriptors;
    }

    public ResultDescriptor[] getResultDescriptors() {
        return resultDescriptors;
        
    }
}