#include "StdAfx.h"
#include "DraggableImageView.h"

DraggableImageView::DraggableImageView(void)
{
	fastimage = NULL;
	image = NULL;
	origin = Point(0,0);
	updatefastimage = 0;
	ownimage = 0;
	title = _T("DraggableImageView");
	dt = 0.05;
}

DraggableImageView::~DraggableImageView(void)
{
	//if(image && ownimage) delete image;
}

int DraggableImageView::OnSetCursor()
{
	SetCursor(env.handcursor);
	return 1;
}

void DraggableImageView::UpdateImage()
{
	updatefastimage = 1;
	InvalidateRgn(hWnd,NULL,FALSE);
	UpdateWindow(hWnd);
}

int DraggableImageView::LoadImage(TCHAR * filename)
{
	if(image && ownimage) delete image;
	image = new Bitmap(filename);
	ownimage = 1;
	origin = Point(0,0);
	if(image==NULL){
		print(L"DraggableImageView.LoadImage: unable to load %s\n",filename);
	} else
		UpdateImage();
	return (image!=NULL);
}

int DraggableImageView::SetImage(Bitmap* img)
{
	image = img;
	ownimage = 0;
	UpdateImage();
	return 1;
}

void DraggableImageView::OnPaint(HWND hWnd, HDC hdc)
{
	Graphics graphics(hdc);

	if(image){
		if(updatefastimage){
			print(L"DraggableImageView.OnPaint: updating cached bitmap\n");
			if(fastimage) delete fastimage;
			fastimage = new CachedBitmap(image,&graphics);
			if(fastimage==NULL){
				print(L"DraggableImageView.OnPaint: unable to create CachedBitmap\n");
			}
			updatefastimage = 0;
		}

		if(fastimage)
			graphics.DrawCachedBitmap(fastimage,origin.X,origin.Y);
	}

	if(current->borderwidth>0){
		// Create a Rect object.
		Rect fillRect(Point(0,0),size);

		// Create a Pen object.
		Pen borderpen(current->bordercolor, current->borderwidth);

		// Draw the rectangle that bounds the client area.
		fillRect.Width--;
		fillRect.Height--;
		graphics.DrawRectangle(&borderpen, fillRect);
	}

}

void DraggableImageView::OnMouseMove()
{
	// Moving the image
	if(env.mouse.LeftButton){
		int dx = env.mouse.Screen.x-env.mouse.DragOrigin.x;
		int dy = env.mouse.Screen.y-env.mouse.DragOrigin.y;

		SetViewPosition(env.mouse.InitialPos.x+dx,env.mouse.InitialPos.y+dy);
	}
}

void DraggableImageView::SetViewPosition(int x, int y)
{
	origin.X = x;
	origin.Y = y;
	if(origin.X>0) origin.X = 0;
	if(origin.Y>0) origin.Y = 0;
	if(origin.X<size.Width-(int)image->GetWidth()) origin.X = size.Width-(int)image->GetWidth();
	if(origin.Y<size.Height-(int)image->GetHeight()) origin.Y = size.Height-(int)image->GetHeight();

	InvalidateRgn(hWnd,NULL,FALSE);
	//UpdateWindow(hWnd);
}

void DraggableImageView::OnLButtonDown()
{
	env.mouse.InitialPos.x = origin.X;
	env.mouse.InitialPos.y = origin.Y;
}


// try to move until the given pt is in the center of the view port
void DraggableImageView::GlideTo(int x, int y)
{
	glidefrom = origin;
	glideto = Point(size.Width/2-x,size.Height/2-y);
	t = 1;
	SetTimer(hWnd,0,1000/glideHz,NULL);
}

void DraggableImageView::OnTimer()
{
	if(t<0){
		KillTimer(hWnd,0);
		return;
	} 
	t -= dt;
	SetViewPosition(t*glidefrom.X+(1-t)*glideto.X,t*glidefrom.Y+(1-t)*glideto.Y);
}