// Timer.cpp : Implementation of cTimer
#include "stdafx.h"
#include "DecalInput.h"
#include "Timer.h"

#include "InputService.h"

/////////////////////////////////////////////////////////////////////////////
// cTimer

STDMETHODIMP cTimer::Start(long Interval)
{
   if( cInputService::g_p == NULL )
   {
      _ASSERT( FALSE );
      return E_FAIL;
   }

   if( Interval <= 0 )
   {
      _ASSERT( FALSE );
      return E_INVALIDARG;
   }

   if( m_bStarted )
      Stop();

   m_nStart = static_cast< long >( ::timeGetTime() );
   m_nInterval = Interval;

   static_cast< IDispatch * >( cInputService::g_p )->AddRef();
   cInputService::g_p->m_timers.push_back( this );

   m_bStarted = true;

	return S_OK;
}

STDMETHODIMP cTimer::Stop()
{
   if( cInputService::g_p == NULL )
   {
      _ASSERT( FALSE );
      return E_FAIL;
   }

   if( !m_bStarted )
      return S_FALSE;

   m_bStarted = false;

   // Remove from the input service
   for( cInputService::cTimerList::iterator i = cInputService::g_p->m_timers.begin(); i != cInputService::g_p->m_timers.end(); ++ i )
   {
      if( *i == this )
      {
         cInputService::g_p->m_timers.erase( i );
         static_cast< IDispatch * >( cInputService::g_p )->Release();
	      return S_OK;
      }
   }

   _ASSERT( FALSE );
   return E_FAIL;
}

STDMETHODIMP cTimer::get_Tag(VARIANT *pVal)
{
   if( pVal == NULL )
   {
      _ASSERT( FALSE );
      return E_POINTER;
   }

   return ::VariantCopy( pVal, &m_tag );
}

STDMETHODIMP cTimer::put_Tag(VARIANT newVal)
{
   m_tag = newVal;

	return S_OK;
}

STDMETHODIMP cTimer::get_Running(VARIANT_BOOL *pVal)
{
   if( pVal == NULL )
   {
      _ASSERT( FALSE );
      return E_POINTER;
   }

   *pVal = ( m_bStarted ) ? VARIANT_TRUE : VARIANT_FALSE;

	return S_OK;
}
