/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/sgx/gui/dynamic_image.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"
#include "sgx/gui/gui.hpp"


sgxGUIDynamicImageParams::sgxGUIDynamicImageParams(const CSGXTexture *pTexture, const CSGXTextureAnimationData *pAnim, const tUINT32 sequenceID, 
												   tUINT32 width, tUINT32 height, CGUIDesign::tJustify formatX, CGUIDesign::tJustify formatY):
m_pAnimationData(pAnim),
m_pTexture(pTexture),
m_Width(width),
m_Height(height),
m_FormatX(formatX),
m_FormatY(formatY)
{
	m_pAnimSequence =  m_pAnimationData->getSequence(sequenceID);
}
	
sgxGUIDynamicImage::sgxGUIDynamicImage(const tINT32 x, const tINT32 y, const sgxGUIDynamicImageParams &params) :
	sgxWidget(x,y, CGUIDesignScreen::widgetAnimatedImage),
	m_SetupParams(params)
{
	m_pSkinParams = CSGXGUI::get()->getCurrentSkin()->getSkinnedDynamicImage(m_SetupParams);
	m_pAnimState =  CSGXTextureAnimationManager::get()->createState(m_SetupParams.m_pAnimSequence, 0);	// start at frame 0
}

void sgxGUIDynamicImage::update(const tREAL32 telaps) {
	if (m_bEnabled) {
		m_pAnimState->update(telaps);
	}
}

tUINT32 sgxGUIDynamicImage::getCurrentCell() const {
	return m_pAnimState->getCurrentCell();
}

const CSGXTexture * sgxGUIDynamicImage::getCurrentTexture() const {
	return m_SetupParams.m_pTexture;
}

void	
sgxGUIDynamicImage::getArea(sgxRect2i &rc) const {
	rc.left = m_X;
	rc.top = m_Y;

	tUINT32 w = m_SetupParams.m_Width;
	tUINT32 h = m_SetupParams.m_Height;
	tUINT32 region = m_pAnimState->getCurrentCell();

	if (w == 0) {
		w =  m_SetupParams.m_pTexture->getRegionWidth(region);
	}
	if (h == 0) {
		h =  m_SetupParams.m_pTexture->getRegionHeight(region);
	}

	CGUIDesign::adjustPosition(rc.left, rc.top, w, h, m_SetupParams.m_FormatX, m_SetupParams.m_FormatY);

	rc.right = rc.left + w;
	rc.bottom = rc.top + h;
}

tBOOL sgxGUIDynamicImage::draw(CSGXDrawSurface *pSurface, const tINT32 offsetX, const tINT32 offsetY) const {
	sgxRect2i rc;
	getArea(rc);

	m_pSkinParams->topleft.x = rc.left+offsetX;
	m_pSkinParams->topleft.y = rc.top+offsetY;
	m_pSkinParams->bottomright.x = rc.right+offsetX;
	m_pSkinParams->bottomright.y = rc.bottom+offsetY;

	m_pSkinParams->enabled = m_bEnabled;
	m_pSkinParams->cursorOver = m_isOver;
	
	m_pSkinParams->m_iCurrentRegion = m_pAnimState->getCurrentCell();

	m_pSkinParams->draw(pSurface);

	return sgxWidget::draw(pSurface, m_pSkinParams->topleft.x, m_pSkinParams->topleft.y);
}
