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.ResultEntryDescriptor;
import org.apache.commons.contract.descriptor.StateDescriptor;
import org.apache.commons.contract.i18n.ParameterMessage;
import org.apache.commons.i18n.LocalizedMessage;
import org.apache.slide.projector.Projector;
import org.apache.slide.projector.constraints.URIConstraints;
import org.apache.slide.projector.context.ProjectorContext;
import org.apache.slide.projector.repository.RepositoryException;

/**
 * @version $Revision: 1.6 $
 */

public class CreateRole implements Processor {
    private final static String ROLENAME = "rolename";
    
    private final static String ROLE = "role";
    private final static String OK = "ok";
    private final static String FAILED = "failed";

    private final static ParameterDescriptor [] parameterDescriptor = new ParameterDescriptor[] {
            new ParameterDescriptor(ROLENAME, new ParameterMessage("createRole/parameter/rolename"), new StringConstraints(1,24)),
        };

    private final static ResultDescriptor[] resultDescriptors = new ResultDescriptor[] {
            new ResultDescriptor(new StateDescriptor(OK, new LocalizedMessage("createRole/state/ok")),
                    new ResultEntryDescriptor[] {
                    new ResultEntryDescriptor(ROLE, new LocalizedMessage("createRole/result/role"), URIConstraints.UNCONSTRAINED)
            }),
            new ResultDescriptor(new StateDescriptor(FAILED, new LocalizedMessage("createRole/state/failed")))
    };
    
    public Result process(Map parameter, Context context) throws Exception {
        String rolename = parameter.get(ROLENAME).toString();
        String state = OK;
        Object role = null;
        try {
        	role = Projector.getRepository().createRole(rolename, ((ProjectorContext)context).getCredentials());	
        } catch ( RepositoryException exception ) {
        	context.addInformation(new Information(Information.ERROR, exception.getLocalizedError(), new String[] { ROLENAME }));
        	state = FAILED;
        }
        return new Result(state, ROLE, role);
    }

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

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