/************************************************************************
 *
 * Licensed Materials - Property of IBM.
 * (C) Copyright IBM Corporation 2003, 2012.  All Rights Reserved.
 * U.S. Government Users Restricted Rights:
 * Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 *
 ************************************************************************/

#ifndef __INTERNAL_SUN_STAR_INTERFACE_QUERY_H_INCLUDE___
#define __INTERNAL_SUN_STAR_INTERFACE_QUERY_H_INCLUDE___

#include "com/sun/star/lang/XUnoTunnel.hpp"
#include "internal/sun/star/uuid/uuid.h"

namespace internal
{
	namespace sun
	{
		namespace star
		{
			namespace interface
			{
				template< typename IInternalFace, typename IUNOFace >
				IInternalFace * QueryInterface( IUNOFace * pUnoFace )
				{
					com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUnoTunnel( pUnoFace, com::sun::star::uno::UNO_QUERY );

					if( ::com::sun::star::lang::XUnoTunnel * pUnoTunnel = xUnoTunnel.is() ? reinterpret_cast< ::com::sun::star::lang::XUnoTunnel* >( xUnoTunnel->getSomething( ::com::sun::star::uno::Sequence<sal_Int8 >( (sal_Int8*)const_cast<char*>( issu::uuidof< ::com::sun::star::lang::XUnoTunnel>::ID ), issu::UUID_LEN ) ) ) : NULL )
						if( /*pUnoTunnel && xUnoTunnel.is() &&*/ pUnoTunnel == xUnoTunnel.get() )//check raw interface pUnoTunnel is same as xUnoTunnel to confirm uno query result is same as pUnoTunnel, which means is not RPC( remote procedure call )
							return reinterpret_cast< IInternalFace* >( xUnoTunnel->getSomething( ::com::sun::star::uno::Sequence<sal_Int8 >( (sal_Int8*)const_cast<char*>( issu::uuidof<IInternalFace>::ID ), issu::UUID_LEN ) ) );

					return NULL;
				}

				template< typename IInternalFace, typename IUNOFace >
				IInternalFace * QueryInterface( const com::sun::star::uno::Reference<IUNOFace> & rxUnoFace )
				{
					return QueryInterface<IInternalFace>( rxUnoFace.get() );
				}

#ifdef _RTL_REF_HXX_
				template< typename T >
				struct Reference : rtl::Reference< T >
				{
					template< typename IUNOFace >
					Reference( IUNOFace * pUnoFace ): rtl::Reference< T >( QueryInterface<T>( pUnoFace ) ){}

					template< typename IUNOFace >
					Reference( const com::sun::star::uno::Reference<IUNOFace> & rxUnoFace ): rtl::Reference< T >( QueryInterface<T>( rxUnoFace ) ){}
				};
#endif
			}
		}
	}
}

namespace issi = ::internal::sun::star::interface;

#endif // __INTERNAL_SUN_STAR_UUID_UUID_H_INCLUDE___