#include "..\inc\myimage.h"
#include "myDirect3D.h"

myImage::myImage(void)
{
	m_surface		= NULL;
	m_width			= -1;
	m_height		= -1;
	m_isVisible		= false;
	m_x				= 0;
	m_y				= 0;
	m_scale			= 1.0;
	m_next			= NULL;
	m_msDisplay		= 0;
	m_startTime		= 0;
}

myImage::~myImage(void)
{
	clean();
}

bool myImage::load(char* filename, bool isVisible)
{
	HRESULT hr;
	D3DXIMAGE_INFO ii;

	hr = D3DXGetImageInfoFromFile(filename,&ii);
	if(FAILED(hr)) return false;
	m_width	 = ii.Width;
	m_height = ii.Height;

	hr = myDirect3D::getDevice()->CreateOffscreenPlainSurface(
		m_width,m_height,
		D3DFMT_A8R8G8B8,
		D3DPOOL_DEFAULT,
		&m_surface,
		NULL
		);
	if(FAILED(hr)) return false;

	hr = D3DXLoadSurfaceFromFile(
		m_surface,
		NULL,
		NULL,
		filename,
		NULL,
		D3DX_DEFAULT,
		0,
		NULL
		);
	if(FAILED(hr)) return false;
								
	setVisible(isVisible);
	myDirect3D::getD3D()->registerImage(this);

	return true;
}

void myImage::setVisible(bool isVisible)
{
	m_isVisible = isVisible;
	if(m_next != NULL)
		m_startTime = GetTickCount();
}

void myImage::setPosition(int x, int y)
{
	m_x = x;
	m_y = y;
}

void myImage::setScale(float f)
{
	m_scale = f;
}

void myImage::setNextAnimImage(myImage* next, int ms)
{
	m_next = next;
	m_msDisplay = ms;

	if(m_isVisible)
		m_startTime = GetTickCount();
}

void myImage::draw()
{
	if(!m_isVisible) return;
	if(m_next != NULL)
	{
		DWORD current = GetTickCount();
		if(((int)(current-m_startTime)) > m_msDisplay)
		{
			m_isVisible = false;
			m_next->setVisible(true);
		}
	}
	LPDIRECT3DSURFACE9 backBuffer;
	myDirect3D::getDevice()->GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO,&backBuffer);
	RECT r;
	r.left		= m_x;
	r.top		= m_y;
	r.right		= m_x + (int)(m_scale*m_width);
	r.bottom	= m_y + (int)(m_scale*m_height);
	myDirect3D::getDevice()->StretchRect(m_surface,NULL,backBuffer,&r,D3DTEXF_NONE);
}

void myImage::clean()
{
	setVisible(false);
	myDirect3D::getD3D()->unregisterImage(this);
	if(m_surface != NULL)
	{
		m_surface->Release();
		m_surface = NULL;
	}

	m_surface		= NULL;
	m_width			= -1;
	m_height		= -1;
	m_isVisible		= false;
	m_x				= -1;
	m_y				= -1;
	m_scale			= -1.0;
	m_next			= NULL;
	m_msDisplay		= -1;
	m_startTime		= 0;
}
