/*
 * $Id: CORBAUserMappingManager.java,v 1.3 2004/11/24 09:26:03 lawern Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 * 
 * Created on 13.07.2004
 *
 * $Log: CORBAUserMappingManager.java,v $
 * Revision 1.3  2004/11/24 09:26:03  lawern
 * Hibernate ist VKC-Geschichte!
 *
 * Revision 1.2  2004/09/20 10:26:11  koppy
 * +javadoc Dokumentation
 *
 * Revision 1.1  2004/08/30 14:49:56  koppy
 * Initiale Version der Workflow-Komponente
 *
 */
package vkc.workflow.service.corba;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import vkc.db.entities.VKCGroup;
import vkc.db.helper.DBHelper;
import vkc.db.serializer.VKCGroupSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.view.WebShare;
import vkc.view.bean.UserInfo;
import vkc.workflow.WfConstants;
import vkc.workflow.WorkflowException;
import vkc.workflow.model.MappingInfo;
import vkc.workflow.service.CORBAWorkflowService;
import vkc.workflow.service.VKCWorkflowService;
import vkc.workflow.service.WfMConnection;
import vkc.workflow.service.manager.UserMappingManager;
import vkc.workflow.util.SharkUtils;
import WorkflowService.AdminMisc;
import WorkflowService.MappingAdministration;
import WorkflowService.NotConnected;
import WorkflowService.ParticipantMap;
import java.sql.Connection;

/**
 * This class represents the CORBA client version
 * of the user mapping manager.
 * 
 * @author Andreas Koop
 */
public class CORBAUserMappingManager implements UserMappingManager {

    private CORBAWorkflowService wfService = null;
    
    public CORBAUserMappingManager( CORBAWorkflowService wfService ){
        this.wfService = wfService;
    }
    
    /** 
     * (non-Javadoc)
     * @see vkc.workflow.service.manager.UserMappingManager#getUserMappings(vkc.workflow.service.WfMConnection, java.lang.String, java.lang.String)
     */
    public List getUserMappings(WfMConnection wfmConn, String pkgId, String pDefId) throws WorkflowException {

        List l = new ArrayList();
        MappingAdministration ma = wfService.getShark()
        				.getAdminInterface().getMappingAdministration();
        
        AdminMisc adminMisc = wfService.getShark().getAdminInterface().getAdminMisc();
        
        Connection conn = null;
    	try {
            ma.connect( wfmConn.getUsername(), wfmConn.getPassword(), wfService.getEngine(), "" );
            adminMisc.connect( wfmConn.getUsername(), wfmConn.getPassword(), wfService.getEngine(), "" );
            
            ParticipantMap [] mappings = ma.getAllParticipantMappings();
            ParticipantMap [] allParticipants = ma.getAllParticipantsFromPkg( pkgId );
            
            conn = WebShare.database.getConnection();
            for (int i = 0; i < allParticipants.length; i++) {
                ParticipantMap map = allParticipants[i];
               
                if(!map.getPackageId().equals( pkgId ))
                    continue;
              
                if( pDefId != null && !map.getProcessDefinitionId().equals( pDefId ))
                    continue;
                
                map = eventuallyUpdateMapping( map, mappings);
                MappingInfo mapping = new MappingInfo();
                mapping.setParticipantId( map.getParticipantId() );
                mapping.setParticipantName( adminMisc.getParticipantName(
                        		pkgId, map.getProcessDefinitionId(), mapping.getParticipantId()));
                mapping.setPkgId( pkgId );
                mapping.setProcDefId( map.getProcessDefinitionId() );
                mapping.setGroupUser( map.getIsGroupUser() );
                if( map.getIsGroupUser() ){
                    VKCGroup gi = VKCGroupSerializer.retrieveGroup( map.getUsername(), conn);
                    if(gi !=null)
                        mapping.setGroup( gi.getName());
                }else{
                    UserInfo ui = VKCUserSerializer.retrieveUserInfo(map.getUsername(), conn );
                    if( ui != null)
                        mapping.setUser( ui.getUsername());
                }
                
                if( mapping.getUser() == null && mapping.getGroup() == null){
                    mapping.setUser( WfConstants.UNKNOWN );
                    mapping.setGroup( WfConstants.UNKNOWN );
                }
                
                l.add( mapping );
            }
            
        } catch (NotConnected e) {
            throw new WorkflowException( "wf.error.notConnected", e);
        } catch (Exception e) {
            throw new WorkflowException( "wf.error.general", e);
        }finally{
            SharkUtils.disconnect( ma );
            SharkUtils.disconnect( adminMisc );
            DBHelper.close(conn);
        }
        
        return l;
    }

    /**
     * @param map
     * @param mappings
     * @return
     */
    private ParticipantMap eventuallyUpdateMapping(ParticipantMap mapDef, ParticipantMap[] mappings) {
        
        for (int i = 0; i < mappings.length; i++) {
            ParticipantMap mapping = mappings[i];
            if(mapping.getParticipantId().equals( mapDef.getParticipantId()))
                return mapping;
        }
        
        return mapDef;
    }

    /** 
     * (non-Javadoc)
     * @see vkc.workflow.service.manager.UserMappingManager#setUserMappings(vkc.workflow.service.WfMConnection, java.util.List)
     */
    public void setUserMappings(WfMConnection conn, List newMappings) throws WorkflowException {
        
        MappingAdministration ma = wfService.getShark()
						.getAdminInterface().getMappingAdministration();

        
        try {
            ma.connect(conn.getUsername(), conn.getPassword(), wfService
                    .getEngine(), "");
            
            for (Iterator iter = newMappings.iterator(); iter.hasNext();) {
		        MappingInfo mi = (MappingInfo) iter.next();
		        
		        // Remove old mapping
		        ma.removeParticipantMappings( mi.getPkgId(),
		                			mi.getProcDefId(), mi.getParticipantId());
		        
		        // Falls nichts ausgewählt wurde, wird kein neuess Mapping erstellt
		        if( ( mi.getUser() == null || mi.getUser().equals(WfConstants.UNKNOWN))
		            && ( mi.getGroup() == null || mi.getGroup().equals(WfConstants.UNKNOWN))){
		            continue;
		        }
		        
		        // replace by new mapping
		        ParticipantMap map = ma.createParticipantMap();
		        map.setPackageId( mi.getPkgId() );
		        map.setProcessDefinitionId( mi.getProcDefId() );
		        map.setParticipantId( mi.getParticipantId() );
		        
		        if( mi.isGroupUser())
		            map.setUsername( mi.getGroup() );
		        else
		            map.setUsername( mi.getUser() );
		        
		        map.setIsGroupUser( mi.isGroupUser() );
		        
		        if(VKCWorkflowService.debug){
		            System.err.println( "Setting mapping " + mi);
		        }
		        ma.addParticipantMapping( map );
            }

        } catch (NotConnected e) {
            throw new WorkflowException("wf.error.notConnected", e);
        } catch (Exception e) {
            throw new WorkflowException("wf.error.mappingFailed", e);
        } finally {
            SharkUtils.disconnect(ma);
            
        }
        
    }

}
