#include "stdafx.h"
#include "ExampleDataObject.h"
#include "RpExamplesPlugin.h"

STDMETHODIMP CRdExampleDataObject::Clone( IRsObject **ppObject )
{
    CComPtr<IRdExampleDataObject> spClone;
    CRpExamplesPlugin::CreateDataObject(&spClone);
    if (!spClone){
        return E_FAIL;
    }
    spClone->SetName(m_bszName);
    spClone->SetAddress(m_bszAddress);
    spClone->SetAge(m_age);

    CComQIPtr<IRsObject> spObj = spClone;
    return spObj.CopyTo(ppObject);
}

STDMETHODIMP CRdExampleDataObject::SetDefault()
{
    m_bszName = L"";
    m_bszAddress = L"";
    m_age = 0;
    m_bDirty = false;
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::SetName(BSTR bszName)
{
    m_bszName = bszName;
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::GetName(BSTR *pbszName)
{
    if (!pbszName){
        return E_INVALIDARG;
    }
    *pbszName = m_bszName;
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::SetAddress(BSTR bszAddress)
{
    m_bszAddress = bszAddress;
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::GetAddress(BSTR *pbszAddress)
{
    if (!pbszAddress){
        return E_INVALIDARG;
    }
    m_bszAddress.CopyTo(pbszAddress);
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::SetAge(int age)
{
    m_age = age;
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::GetAge(int *pAge)
{
    if (!pAge){
        return E_INVALIDARG;
    }
    *pAge = m_age;
    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::IsDirty()
{
    return m_bDirty ? S_OK : S_FALSE;
}

STDMETHODIMP CRdExampleDataObject::Save( IStream *pStream, RtBOOL fClearDirty )
{
    HRESULT hr;
    if (FAILED(hr = m_bszName.WriteToStream(pStream))){
        return hr;
    }

    if (FAILED(hr = m_bszAddress.WriteToStream(pStream))){
        return hr;
    }

    if (FAILED(hr = pStream->Write(&m_age, sizeof(m_age), NULL))){
        return hr;
    }

    if (fClearDirty){
        m_bDirty = false;
    }

    return S_OK;
}

STDMETHODIMP CRdExampleDataObject::Load( IStream *pStream, RtObjFileHeaderInfo *pObjFileHeaderInfo )
{
    HRESULT hr;
    if (FAILED(hr = m_bszName.ReadFromStream(pStream))){
        return E_FAIL;
    }
    if (FAILED(hr = m_bszAddress.ReadFromStream(pStream))){
        return E_FAIL;
    }

    // read age only if the version is greater than 1
    if (pObjFileHeaderInfo->objFileVersion>EXAMPLEDO_STREAM_VERSION_1)
    {
        if (FAILED(hr = pStream->Read(&m_age, sizeof(m_age), NULL)))
        {
            return hr;
        }
    }

    return S_OK;
}

