/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: fileread.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 "hxwintyp.h"
#include "hxcom.h"
#include "hxresult.h"
#include "hxcomm.h"
#include "ihxpckts.h"
#include "hxfiles.h"

// hxmisc
#include "baseobj.h"

// pxcomlib
#include "fileread.h"

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

CHXFileReader::CHXFileReader()
{
    m_lRefCount           = 0;
    m_pContext            = NULL;
    m_pFileObject         = NULL;
    m_pResponse           = NULL;
    m_pCommonClassFactory = NULL;
    m_ulState             = kStateConstructed;
    m_ulFlags             = 0;
    m_ulCurrentOffset     = 0;
    m_ulReqOffset         = 0;
    m_ulReqNumBytes       = 0;
}

CHXFileReader::~CHXFileReader()
{
    Deallocate();
}

void CHXFileReader::Deallocate()
{
    HX_RELEASE(m_pContext);
    HX_RELEASE(m_pFileObject);
    HX_RELEASE(m_pResponse);
    HX_RELEASE(m_pCommonClassFactory);
}

STDMETHODIMP CHXFileReader::Init(IUnknown*              pContext,
                                 IHXFileObject*        pFileObject,
                                 BOOL                   bCanPreload,
                                 BOOL                   bCanCache,
                                 CHXFileReaderResponse* pResponse)
{
    HX_RESULT retVal = HXR_OK;

    if (pContext && pFileObject && pResponse &&
        !bCanPreload && !bCanCache) // XXXMEH - for now, no preload or caching
    {
        if (m_ulState == kStateConstructed)
        {
            // Save arguments into members
            HX_RELEASE(m_pContext);
            m_pContext = pContext;
            m_pContext->AddRef();
            HX_RELEASE(m_pFileObject);
            m_pFileObject = pFileObject;
            m_pFileObject->AddRef();
            HX_RELEASE(m_pResponse);
            m_pResponse = pResponse;
            m_pResponse->AddRef();
            // Save flags
            if (bCanPreload)
            {
                m_ulFlags |= kFlagCanPreload;
            }
            if (bCanCache)
            {
                m_ulFlags |= kFlagCanCache;
            }

            // Get an IHXCommonClassFactory interface
            HX_RELEASE(m_pCommonClassFactory);
            retVal = m_pContext->QueryInterface(IID_IHXCommonClassFactory,
                                                (void**) &m_pCommonClassFactory);
            if (SUCCEEDED(retVal))
            {
                // Set the new state
                m_ulState = kStateInitPending;
                // Init the file object
                m_pFileObject->Init(HX_FILE_READ | HX_FILE_BINARY, this);
            }
        }
        else
        {
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_INVALID_PARAMETER;
    }

    return retVal;
}

STDMETHODIMP CHXFileReader::Read(UINT32 ulOffset, UINT32 ulNumBytes)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateReady)
    {
        // Save the read information
        m_ulReqOffset   = ulOffset;
        m_ulReqNumBytes = ulNumBytes;
        // Are we already at the right place in the file?
        if (ulOffset != m_ulCurrentOffset)
        {
            // We need to seek to the new offset
            //
            // Set the state
            m_ulState = kStateSeekPending;
            // Call IHXFileObject::Seek()
            m_pFileObject->Seek(ulOffset, FALSE);
        }
        else
        {
            // We're already at the right offset, just read
            //
            // Set the state
            m_ulState = kStateReadPending;
            // Call IHXFileObject::Read()
            m_pFileObject->Read(ulNumBytes);
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CHXFileReader::Shutdown()
{
    HX_RESULT retVal = HXR_OK;

    if (m_pResponse)
    {
        if (m_ulState == kStateConstructed)
        {
            // We haven't Init()'d the file object yet,
            // so there's no need to close it. We can just
            // call back with ShutdownDone(). No need to change
            // the state either
            m_pResponse->ShutdownDone();
        }
        else if (m_ulState == kStateReady)
        {
            // No pending callback, but we do need to close
            // the file.
            //
            // Set the state
            m_ulState = kStateClosePending;
            // Close the file
            m_pFileObject->Close();
        }
        else if (m_ulState == kStateInitPending ||
                 m_ulState == kStateSeekPending ||
                 m_ulState == kStateReadPending)
        {
            // We are awaiting a callback when we got this 
            // Shutdown(). Therefore, we will go ahead and call
            // Close() on the file object, and then make sure
            // we don't do anything in these callbacks.
            //
            // Set the state
            m_ulState = kStateClosePending;
            //
            m_pFileObject->Close();
        }
        else if (m_ulState == kStateClosePending)
        {
            // We got a Shutdown() while after we had already called
            // Close() on the file object. Nothing to do here
            // since we will call ShutdownDone() already after we
            // get the CloseDone().
        }
        else
        {
            // Unknown state
            retVal = HXR_UNEXPECTED;
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CHXFileReader::QueryInterface(REFIID riid, void** ppvObj)
{
    HX_RESULT retVal = HXR_OK;

    if (IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppvObj = this;
    }
    else if (IsEqualIID(riid, IID_IHXFileResponse))
    {
        AddRef();
        *ppvObj = (IHXFileResponse*) this;
    }
    else
    {
        *ppvObj = NULL;
        retVal  = HXR_NOINTERFACE;
    }

    return retVal;
}

STDMETHODIMP_(UINT32) CHXFileReader::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

STDMETHODIMP_(UINT32) CHXFileReader::Release()
{
    
    if (InterlockedDecrement(&m_lRefCount) > 0)
    {
        return m_lRefCount;
    }

    delete this;

    return 0;
}

STDMETHODIMP CHXFileReader::InitDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateInitPending)
    {
        // Set the state
        m_ulState  = (SUCCEEDED(status) ? kStateReady : kStateConstructed);
        // Tell the response interface we've initialized
        m_pResponse->InitDone(status);
    }
    else if (m_ulState == kStateClosePending)
    {
        // We got a Shutdown() while we were waiting
        // for the InitDone() callback. Therefore, do 
        // nothing here.
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CHXFileReader::CloseDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateClosePending)
    {
        // Set the state
        m_ulState = kStateReady;
        // Tell the response interface that we've shutdown
        m_pResponse->ShutdownDone();
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CHXFileReader::ReadDone(HX_RESULT status, IHXBuffer* pBuffer)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateReadPending)
    {
        // Set the state
        m_ulState = kStateReady;
        // Did we succeed in reading?
        if (SUCCEEDED(status) && pBuffer)
        {
            // We successfully read the number of bytes
            //
            // Update the current offset
            m_ulCurrentOffset += pBuffer->GetSize();
            // Tell the response interface
            m_pResponse->ReadDone(status, pBuffer);
        }
        else
        {
            // We failed to read
            //
            // Tell the response interface
            m_pResponse->ReadDone(status, NULL);
        }
    }
    else if (m_ulState == kStateClosePending)
    {
        // We got a Shutdown() while we were waiting to
        // get this ReadDone() callback. Therefore we do
        // nothing here.
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

STDMETHODIMP CHXFileReader::WriteDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_NOTIMPL;

    return retVal;
}

STDMETHODIMP CHXFileReader::SeekDone(HX_RESULT status)
{
    HX_RESULT retVal = HXR_OK;

    if (m_ulState == kStateSeekPending)
    {
        if (SUCCEEDED(status))
        {
            // We successfully seeked - update the current offset
            m_ulCurrentOffset = m_ulReqOffset;
            // Set the state
            m_ulState = kStateReadPending;
            // Now read the saved number of bytes
            m_pFileObject->Read(m_ulReqNumBytes);
        }
        else
        {
            // We failed to seek
            //
            // Set the state
            m_ulState = kStateReady;
            // Tell the response interface
            m_pResponse->ReadDone(status, NULL);
        }
    }
    else if (m_ulState == kStateClosePending)
    {
        // We got a Shutdown() while we were waiting on
        // this SeekDone() callback. Therefore, do nothing
        // here.
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }

    return retVal;
}

