#include "GfxEnvRZA2M.h"

extern "C" void FlipFramebuffer();
extern "C" void CopyBuffer(int x1, int y1, int width, int height);

CGfxEnvRZA2M::CGfxEnvRZA2M(
    const SurfaceMode_t& eSurfaceMode,
    const CGUICommonEnums::ImageType_t& eScreenFormat,
    const eC_UInt& uiWidth,
    const eC_UInt& uiHeight,
    const eC_UInt& uiBufferCount,
    void** ppkBuffers,
    const eC_Bool& bResizable) :
    CGfxEnv(eSurfaceMode, eScreenFormat, uiWidth, uiHeight, uiBufferCount, ppkBuffers, bResizable)
{
}

CGfxEnvRZA2M::~CGfxEnvRZA2M(void)
{
}

eC_Bool CGfxEnvRZA2M::CreateInstance(
    const SurfaceMode_t& eSurfaceMode,
    const CGUICommonEnums::ImageType_t& eScreenFormat,
    const eC_UInt& uiWidth,
    const eC_UInt& uiHeight,
    const eC_UInt& uiBufferCount,
    void** ppkBuffers,
    const eC_Bool& bResizable)
{
    eC_Bool bInstanceCreated = false;
    if (!CGUIComponentManager::GetInstance().HasGfxEnv())
    {
        CGfxEnvRZA2M* pkGfxEnv = new CGfxEnvRZA2M(
            eSurfaceMode, eScreenFormat,
            uiWidth, uiHeight,
            uiBufferCount, ppkBuffers, bResizable);
        if (pkGfxEnv)
        {
            CGUIComponentManager::GetInstance().SetGfxEnv(pkGfxEnv);
            bInstanceCreated = true;
        }
    }
    return bInstanceCreated;
}

eC_Bool CGfxEnvRZA2M::RefreshScreen(const CGUIRect& rkInvalidatedArea)
{
    eC_Int iX1 = eC_ToInt(eC_Floor(rkInvalidatedArea.GetX1()));
    eC_Int iY1 = eC_ToInt(eC_Floor(rkInvalidatedArea.GetY1()));
    eC_Int iRectWidth = eC_ToInt(rkInvalidatedArea.GetWidth()) + 1;
    eC_Int iRectHeight = eC_ToInt(rkInvalidatedArea.GetHeight()) + 1;
    
    if (iX1 < 0)
    {
        iRectWidth += iX1;
        iX1 = 0;
    }
    if (iY1 < 0)
    {
        iRectHeight += iY1;
        iY1 = 0;
    }

    if (iX1 + iRectWidth > m_uiWidth)
    {
        iRectWidth = m_uiWidth - iX1;
    }
    if (iY1 + iRectHeight > m_uiHeight)
    {
        iRectHeight = m_uiHeight - iY1;
    }
    
    if ((iRectWidth > 0) && (iRectHeight > 0))
    {
        //GUILOG(GUI_TRACE_DEBUG, "refresh: " + eC_String(iX1) + "," + eC_String(iY1) + " (" + eC_String(iRectWidth) + "x" + eC_String(iRectHeight) + "\n");
        CopyBuffer(iX1, iY1, iRectWidth, iRectHeight);
    }
    return true;
}

void CGfxEnvRZA2M::EndOfRefresh()
{
    FlipFramebuffer();
}
