/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: pxcmpmgr.cpp,v 1.1.26.1 2004/07/09 01:54:47 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

// include
#include "hxtypes.h"
#include "hxcom.h"
#include "hxplugn.h"
#include "hxcomm.h"

// hxcont
#include "hxslist.h"
#include "hxmap.h"

// hxmisc
#include "baseobj.h"

// pxcomlib
#include "pxcmpmgr.h"

// hxdebug
#include "hxheap.h"
#ifdef _DEBUG
#undef HX_THIS_FILE		
static char HX_THIS_FILE[] = __FILE__;
#endif

PXComponentManager::PXComponentManager()
{
    m_pComponentList = NULL;
    m_pActiveMap     = NULL;
}

PXComponentManager::~PXComponentManager()
{
    ReleaseAllComponents();
    HX_DELETE(m_pComponentList);
    ClearActiveMap();
    HX_DELETE(m_pActiveMap);
}

STDMETHODIMP PXComponentManager::Init(IUnknown* pContext, REFIID riid)
{
    HX_RESULT                  retVal   = HXR_OK;
    IHXCommonClassFactory*    pFactory = NULL;
    IHXPluginGroupEnumerator* pEnum    = NULL;

    if (pContext)
    {
        // Clear out any current components
        ReleaseAllComponents();
        HX_DELETE(m_pComponentList);
        // Clear any existing active map
        ClearActiveMap();
        HX_DELETE(m_pActiveMap);

        // Allocate a new component list
        m_pComponentList = new CHXSimpleList();
        if (m_pComponentList)
        {
            // Allocate a new active map
            m_pActiveMap = new CHXMapStringToOb();
            if (m_pActiveMap)
            {
                // First try and QI the context for IHXPluginGroupEnumerator
                HX_RESULT rv = pContext->QueryInterface(IID_IHXPluginGroupEnumerator, (void**) &pEnum);
                if (FAILED(rv))
                {
                    // Get an IHXCommonClassFactory interface
                    retVal = pContext->QueryInterface(IID_IHXCommonClassFactory, (void**) &pFactory);
                    if (SUCCEEDED(retVal))
                    {
                        // Get an IHXPluginGroupEnumerator interface
                        retVal = pFactory->CreateInstance(CLSID_IHXPluginGroupEnumerator, (void**) &pEnum);
                    }
                }
                if (SUCCEEDED(retVal))
                {
                    // Initialize with the IID
                    retVal = pEnum->Init(riid);
                    if (SUCCEEDED(retVal))
                    {
                        // Get the number of codecs
                        UINT32 ulNumComponents = pEnum->GetNumOfPlugins();
                        // Get an interface to each codec
                        for (UINT32 i = 0; i < ulNumComponents; i++)
                        {
                            IUnknown* pComponent = NULL;
                            retVal               = pEnum->GetPlugin(i, pComponent);
                            if (SUCCEEDED(retVal))
                            {
                                // See if it supports IHXPlugin. If it does, then
                                // call InitPlugin(). It's OK if it doesn't support IHXPlugin
                                IHXPlugin* pPlugin = NULL;
                                HX_RESULT rv        = pComponent->QueryInterface(IID_IHXPlugin,
                                                                                 (void**) &pPlugin);
                                if (SUCCEEDED(rv))
                                {
                                    // Call IHXPlugin::InitPlugin()
                                    retVal = pPlugin->InitPlugin(pContext);
                                }
                                HX_RELEASE(pPlugin);

                                if (SUCCEEDED(retVal))
                                {
                                    // Addref the component before it goes into the list
                                    pComponent->AddRef();
                                    // Add this codec to the list
                                    m_pComponentList->AddTail((void*) pComponent);
                                }
                            }
                            HX_RELEASE(pComponent);

                            if (FAILED(retVal))
                            {
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                retVal = HXR_OUTOFMEMORY;
            }
        }
        else
        {
            retVal = HXR_OUTOFMEMORY;
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    HX_RELEASE(pEnum);
    HX_RELEASE(pFactory);

    if (FAILED(retVal))
    {
        ReleaseAllComponents();
        HX_DELETE(m_pComponentList);
        ClearActiveMap();
        HX_DELETE(m_pActiveMap);
    }

    return retVal;
}

STDMETHODIMP PXComponentManager::IsComponentPresent(const char* pszID,  BOOL* pbPresent)
{
    HX_RESULT retVal = HXR_OK;

    if (pszID && pbPresent)
    {
        // Set defaults
        *pbPresent = FALSE;
        if (m_pComponentList)
        {
            CHXString cQueryStr(pszID);
            LISTPOSITION pos = m_pComponentList->GetHeadPosition();
            while (pos)
            {
                IUnknown* pComponent = (IUnknown*) m_pComponentList->GetNext(pos);
                if (pComponent)
                {
                    const char* pszComponentID = NULL;
                    retVal                     = GetID(pComponent, pszComponentID);
                    if (SUCCEEDED(retVal))
                    {
                        CHXString cComponentStr(pszComponentID);
                        if (cQueryStr == cComponentStr)
                        {
                            *pbPresent = TRUE;
                            break;
                        }
                    }
                }
            }
        }
        else
        {
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

STDMETHODIMP PXComponentManager::GetComponent(const char* pszID,  BOOL* pbPresent, IUnknown** ppComponent)
{
    HX_RESULT retVal = HXR_OK;

    if (pszID && pbPresent && ppComponent)
    {
        // Set defaults
        *pbPresent   = FALSE;
        *ppComponent = NULL;

        if (m_pComponentList)
        {
            CHXString cQueryStr(pszID);
            LISTPOSITION pos = m_pComponentList->GetHeadPosition();
            while (pos)
            {
                IUnknown* pListComponent = (IUnknown*) m_pComponentList->GetNext(pos);
                if (pListComponent)
                {
                    const char* pszComponentID = NULL;
                    retVal                     = GetID(pListComponent, pszComponentID);
                    if (SUCCEEDED(retVal))
                    {
                        CHXString cComponentStr(pszComponentID);
                        if (cQueryStr == cComponentStr)
                        {
                            *pbPresent   = TRUE;
                            *ppComponent = pListComponent;
                            (*ppComponent)->AddRef();
                            break;
                        }
                    }
                }
            }
        }
        else
        {
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

STDMETHODIMP PXComponentManager::SetActiveComponent(const char* pszID)
{
    HX_RESULT retVal = HXR_OK;

    if (pszID)
    {
        if (m_pActiveMap)
        {
            // Is there already an entry for this string?
            void *pVoid = NULL;
            if (!m_pActiveMap->Lookup(pszID, pVoid))
            {
                // No entry for this string, so add one - doesn't matter
                // what we put for the target of the map (the void*) - we'll
                // never use it - it's just important that a map entry EXISTS.
                m_pActiveMap->SetAt(pszID, (void*) 1);
            }
        }
        else
        {
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

STDMETHODIMP PXComponentManager::ReleaseInactiveComponents()
{
    HX_RESULT retVal = HXR_OK;

    if (m_pComponentList && m_pActiveMap)
    {
        // Run through the codec list, seeing if the
        // codec is on the active list. If it's not,
        // then get rid of it.
        LISTPOSITION pos = m_pComponentList->GetHeadPosition();
        while (pos)
        {
            IUnknown* pComponent = (IUnknown*) m_pComponentList->GetAt(pos);
            if (pComponent)
            {
                // Get the id string
                const char* pszID  = NULL;
                retVal             = GetID(pComponent, pszID);
                if (SUCCEEDED(retVal))
                {
                   // Is the id string in the map?
                   void *pVoid = NULL;
                   if (!m_pActiveMap->Lookup(pszID, pVoid))
                   {
                       // The id string IS NOT in the map, so the codec is
                       // inactive, so we can release it and remove it
                       // from the list
                       HX_RELEASE(pComponent);
                       pos = m_pComponentList->RemoveAt(pos);
                   }
                   else
                   {
                       m_pComponentList->GetNext(pos);
                   }
                }
            }
            else
            {
               retVal = HXR_FAIL;
            }

            if (FAILED(retVal))
            {
                break;
            }
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

void PXComponentManager::ReleaseAllComponents()
{
    if (m_pComponentList)
    {
        // Release all codecs
        LISTPOSITION pos = m_pComponentList->GetHeadPosition();
        while (pos)
        {
            IUnknown* pComponent = (IUnknown*) m_pComponentList->GetNext(pos);
            HX_RELEASE(pComponent);
        }
        // Clear the list object
        m_pComponentList->RemoveAll();
    }
}

void PXComponentManager::ClearActiveMap()
{
    if (m_pActiveMap)
    {
        // Clear all map entries
        m_pActiveMap->RemoveAll();
    }
}

