// -----------------------------------------------------------------------------
// CMediatorServerCommandHandler::CancelCommands
//  
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void CMediatorServerCommandHandler::CancelCommands( MMediatorCommandObserver* aObserver,
                                                    MMediatorCommandResponseObserver* aResponseObserver )
    {
    LOG(_L("[Mediator Server]\t CMediatorServerCommandHandler::CancelCommand"));
    
    // loop through list of pending commands
    for ( TInt i = iCommandPendingList.Count()-1; i >= 0; i-- )
        {
        
        CCommand* commandPtr = iCommandPendingList[i];
        
        if ( commandPtr )
            {
            
            TBool commandCanceled = EFalse;
            
            // This client has registered the command, and some other client has issued it
            // -> give an error response to the issuer
            if ( aObserver == commandPtr->Observer() )
                {
                TRAP_IGNORE( commandPtr->ResponseObserver()->CommandResponseL( commandPtr->Domain(),
                                                                               commandPtr->Category(),
                                                                               commandPtr->Id(),
                                                                               KErrMediatorCommandRemoved,
                                                                               KNullDesC8 ) );
                commandCanceled = ETrue;                                                                               
                }
            
            // This client has issued the command
            // -> inform the client which registered the command that it is canceled
            if ( aResponseObserver == commandPtr->ResponseObserver() )
                {
                TRAP_IGNORE( commandPtr->Observer()->CancelMediatorCommandL( commandPtr->Domain(),
                                                                             commandPtr->Category(),
                                                                             commandPtr->Id() ) );
                commandCanceled = ETrue;                                                                             
                }
            
            // pending command was registered and/or issued by this client, so now it can be removed
            // from the list
            if ( commandCanceled )
                {
                iCommandPendingList.Remove( i );
                delete commandPtr;
                }
            
            }
        
        }

    }
// -----------------------------------------------------------------------------
// CMediatorServerCommandHandler::TimerCallBack
//  
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void CMediatorServerCommandHandler::TimerCallBack( TUid aDomain, 
                                                   TUid aCategory, 
                                                   TInt aCommandId )
    {
    LOG(_L("[Mediator Server]\t CMediatorServerCommandHandler::TimerCallBack"));
    TBool found = EFalse;
    for ( TInt index = 0; index < iCommandPendingList.Count() && !found; index ++ )
        {
        CCommand* commandPtr = iCommandPendingList[index];
        if ( commandPtr )
            {
            if ( ( aDomain == commandPtr->Domain() )
                 && ( aCategory == commandPtr->Category() )
                 && ( aCommandId == commandPtr->Id() ) )
                {
                // We have found the correct command --> ignore the leave 
                // Send the response to initiator with timeout error
                TRAP_IGNORE( commandPtr->ResponseObserver()->CommandResponseL( aDomain,
                                                                               aCategory,
                                                                               aCommandId,
                                                                               KErrMediatorTimeout,
                                                                               KNullDesC8 ) );
                // And clear the responder side also                                                                  
                TRAP_IGNORE( commandPtr->Observer()->MediatorCommandTimeoutL( aDomain,
                                                                              aCategory,
                                                                              aCommandId ) );                                                                  
                // Remove the command from list, free memory && stop looping
                iCommandPendingList.Remove( index );
                delete commandPtr;
                commandPtr = NULL;
                found = ETrue;                                                                  
                }
            }
        }
    }
// -----------------------------------------------------------------------------
// CMediatorServerCommandHandler::CancelCommandL
//  
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void CMediatorServerCommandHandler::CancelCommand( 
                                        TMediatorCategory aCategory, 
                                        MediatorService::TCommand aCommand )
    {
    LOG(_L("[Mediator Server]\t CMediatorServerCommandHandler::CancelCommand"));
    TBool found = EFalse;
    for ( TInt index = 0; index < iCommandPendingList.Count() && !found; index ++ )
        {
        CCommand* commandPtr = iCommandPendingList[index];
        if ( commandPtr )
            {
            TUid domain = aCategory.iDomain;
            TUid category = aCategory.iCategory;
            TInt commandId = aCommand.iCommandId;
            if ( ( domain == commandPtr->Domain() )
                 && ( category == commandPtr->Category() )
                 && ( commandId == commandPtr->Id() ) )
                {
                // We have found the correct command --> cancel it 
                TRAP_IGNORE( commandPtr->Observer()->CancelMediatorCommandL( domain,
                                                                             category,
                                                                             commandId ) );
                // Remove the command from list, free memory && stop looping
                iCommandPendingList.Remove( index );
                delete commandPtr;
                commandPtr = NULL;
                found = ETrue;                                                                  
                }
            }
        }
    }
// -----------------------------------------------------------------------------
// CMediatorServerObjectHandler::ClearRegistrations
//  
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//  
void CMediatorServerObjectHandler::ClearRegistrations( 
                          MMediatorServerEventObserver* aEventObserver, 
                          MMediatorCommandObserver* aCommandObserver,
                          MMediatorServerNotificationObserver* aNotifObserver )
    {
    LOG(_L("[Mediator Server]\t CMediatorServerObjectHandler::ClearRegistrationsL"));
    
    // Clear all pending subscriptions -- loop through domains
    for ( TInt index = iDomainList.Count()-1; index >= 0; index-- )
        {
        CDomain* domainPtr = iDomainList[index];
        if ( domainPtr )
            {
            // Loop through categories
            for( TInt index2 = domainPtr->CategoryCount()-1; index2 >= 0; index2-- )
                {
                CCategory* categoryPtr = domainPtr->GetCategory( index2 );
                if ( categoryPtr )
                    {
                    // Loop through events within category
                    for ( TInt index3 = categoryPtr->EventCount()-1; index3 >= 0; index3-- )
                        {
                        CEvent* eventPtr = categoryPtr->GetEvent( index3 );
                        if ( eventPtr )
                            {
                            // Unregister if found --> ignore the return value
                            eventPtr->RemoveObserver( aEventObserver );
                            }
                        eventPtr = NULL;
                        }
                    RCommandList removedCommands;
                    // Loop through commands within category
                    for ( TInt index4 = categoryPtr->CommandCount()-1; index4 >= 0; index4-- )
                        {
                        CCommand* commandPtr = categoryPtr->GetCommand( index4 );
                        if ( commandPtr )
                            {
                            if ( commandPtr->Observer() == aCommandObserver )
                                {
                                // Found the command --> remove it and append
                                // to notification list
                                TCommand removeCommand;
                                removeCommand.iCommandId = commandPtr->Id();
                                removeCommand.iVersion = commandPtr->Version();
                                removedCommands.Append( removeCommand );
                                categoryPtr->RemoveCommand( index4 );
                                delete commandPtr;
                                commandPtr = NULL;
                                }
                            }
                        commandPtr = NULL;
                        }
                    // Notify command removal
                    if ( removedCommands.Count() > 0 )
                        {
                        CommandsRemoved( domainPtr->DomainUid(),
                                         categoryPtr->CategoryUid(),
                                         removedCommands );
                        }
                    removedCommands.Reset();
                    }
                categoryPtr = NULL;
                }
            }
        domainPtr = NULL;
        }
    
    // Loop through the notification subscriber array still
    TBool found = EFalse;
    for ( TInt index = 0; index < iObserverList.Count() && !found; index++ )
        {
        if ( iObserverList[index] == aNotifObserver )
            {
            iObserverList.Remove( index );
            found = ETrue;
            }
        }
    }
// -----------------------------------------------------------------------------
// CMediatorServerCommandHandler::IssueCommandL
//  
// (other items were commented in a header).
// -----------------------------------------------------------------------------
//
void CMediatorServerCommandHandler::IssueCommandL( 
                                        TMediatorCategory aCategory, 
                                        MediatorService::TCommand aCommand,
                                        const TDesC8& aData,
                                        TCapabilitySet aCaps,
                                        MMediatorCommandResponseObserver* aObserver )
    {
    LOG(_L("[Mediator Server]\t CMediatorServerCommandHandler::IssueCommandL"));
    CCategory* category = iObjectHandler.CategoryL( aCategory );
    if ( category )
        {
        // Find the command from register list
        TInt ignore = 0;
        CCommand* commandPtr = category->FindCommand( aCommand.iCommandId, ignore );
        if ( !commandPtr )
            {
            ERROR_TRACE(Print(_L("[Mediator] CMediatorServerCommandHandler::IssueCommandL: Command %d not found in category %d of domain %d\n"), aCommand.iCommandId, 
                                                                                                                                                   aCategory.iCategory.iUid,
                                                                                                                                                   aCategory.iDomain.iUid ) );
            
            User::Leave( KErrMediatorCommandNotFound );
            }     
        // Then check the capabilities && the version information
        // Capabilities are checked so that boolean ETrue is returned
        // when all parameter caps can be found from aCaps
        if ( !aCaps.HasCapabilities( commandPtr->Policy() ) )
            {
#ifdef _DEBUG
            for ( TInt index = 0; index < ECapability_Limit; index++ )
                {
                TCapabilitySet commandCaps = commandPtr->Policy();
                TBool command = commandCaps.HasCapability( (TCapability) index );
                TBool requestor = aCaps.HasCapability( (TCapability) index );
                if ( command && !requestor )
                    {
                    ERROR_TRACE(Print(_L("[Mediator] CMediatorServerCommandHandler::IssueCommandL: capability %d missing\n"), index ));
                    ERROR_TRACE(Print(_L("[Mediator] Capability error when issuing command %d in category %d of domain %d\n"), aCommand.iCommandId, 
                                                                                                                                 aCategory.iCategory.iUid,
                                                                                                                                 aCategory.iDomain.iUid ) );
                    }
                }
#endif    
            User::Leave( KErrPermissionDenied );
            }
        // Check (major) version match
        if ( aCommand.iVersion.iMajor != commandPtr->Version().iMajor )
            {
            ERROR_TRACE(Print(_L("[Mediator] CMediatorServerCommandHandler::IssueCommandL: registered=%d, issued=%d\n"), 
                                                                                        commandPtr->Version().iMajor,
                                                                                        aCommand.iVersion.iMajor ));
            ERROR_TRACE(Print(_L("[Mediator] Version error when issuing command %d in category %d of domain %d\n"), aCommand.iCommandId, 
                                                                                                                      aCategory.iCategory.iUid,
                                                                                                                      aCategory.iDomain.iUid ) );
            // There's a major version mismatch
            User::Leave( KErrMediatorVersionMismatch );
            }
        
        // If ok, issue to command to client
        // Make the new command, set initiator and responder
        // We don't need to command data for the pending list
        CCommand* newCommand = CCommand::NewL( aCommand );
        CleanupStack::PushL( newCommand );
        
        newCommand->SetResponseObserver( aObserver );
        newCommand->SetObserver( commandPtr->Observer() );
        newCommand->SetDomain( aCategory.iDomain );
        newCommand->SetCategory( aCategory.iCategory );
        newCommand->SetTimeout( commandPtr->Timeout() );
        
        // Start command timing, if it is not an infinite command
        if ( commandPtr->Timeout() != KMediatorTimeoutInfinite )
            {
            // Start timeout timer ( request callback here )
            newCommand->StartTimer( this );    
            }
                
        iCommandPendingList.AppendL( newCommand );
        
        CleanupStack::Pop( newCommand );
        
        // Now send the command to correct responder --> we have it pending
        commandPtr->Observer()->MediatorCommandL( aCategory.iDomain,
                                                  aCategory.iCategory,
                                                  aCommand.iCommandId,
                                                  aCommand.iVersion,
                                                  aData );
        }
    }