#include "StdAfx.h"
#include "ImageView.h"

ImageView::ImageView(void)
{
	image = NULL;
	ownimage = 0;
	updatefastimage = 0;
	fastimage = NULL;
	title = _T("ImageView");
	draggable = 0;
}

ImageView::~ImageView(void)
{
	//if(image && ownimage) delete image;
	//if(fastimage) delete fastimage;
	fastimage = NULL;
	image = NULL;
}

void ImageView::UpdateImage()
{
	if(image){
		SetSize(image->GetWidth(),image->GetHeight());
		updatefastimage = 1;
	}
	InvalidateRgn(hWnd,NULL,FALSE);
	UpdateWindow(hWnd);
}

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

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

void ImageView::Draw(Graphics& graphics)
{
	try {
		if(updatefastimage){
			// print(L"ImageView.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,0,0);
	} catch(...) {
		print(L"ImageView::Draw: exception caught.\n");
	}
}

/*
void ImageView::OnMouseMove()
{
	if(draggable){
		// Moving the image
		if(env.mouse.LeftButton && image){
			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);
		}
	} else {
		SkinnableWindow::OnMouseMove();
	}
}

void ImageView::SetViewPosition(int x, int y)
{
	if(image){
		SkinnableWindow * parent = (SkinnableWindow*)GetWindowLongPtr(hWndParent,GWL_USERDATA);
		if(parent){
			// clamp the location by the parent's borders
			if(x>0) x = 0;
			if(y>0) y = 0;
			if(x<size.Width-(int)image->GetWidth()) x = parent->size.Width-(int)image->GetWidth();
			if(y<size.Height-(int)image->GetHeight()) y = parent->size.Height-(int)image->GetHeight();
		}
	}

	SetLocation(x,y);
}

void ImageView::OnLButtonDown()
{
	if(draggable){
		env.mouse.InitialPos.x = location.X;
		env.mouse.InitialPos.y = location.Y;
	} else {
		SkinnableWindow::OnLButtonDown();
	}
}
*/