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

DraggableImageView::DraggableImageView(void)
{
	title = _T("DraggableImageView");
	dt = 0.05;
}

DraggableImageView::~DraggableImageView(void)
{
}

int DraggableImageView::Create(HWND parent)
{
	SkinnableWindow::Create(parent);
	container.SetLocation(1,1);
	container.SetSize(size.Width-2,size.Height-2);
	canvas.SetLocation(0,0);
	container.Create(hWnd);
	canvas.draggable = 1;
	canvas.Create(container.hWnd);
	return 1;
}

void DraggableImageView::OnSize(int cx, int cy)
{
	SkinnableWindow::OnSize(cx,cy);
	container.SetSize(cx-2,cy-2);
	SetMoveableRect();
}

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

int DraggableImageView::LoadImage(TCHAR * filename)
{
	int result = canvas.LoadImage(filename);
	if(result){
		SetMoveableRect();
	}
	return result;
}

int DraggableImageView::SetImage(Bitmap* img)
{
	int result = canvas.SetImage(img);
	if(result){
		SetMoveableRect();
	}
	return result;
}

void DraggableImageView::SetMoveableRect()
{
	if(canvas.image==NULL) return;

	int x,y,w,h;
	if(container.size.Height>(int)canvas.image->GetHeight()){
		y = 0;
		h = canvas.image->GetHeight()-container.size.Height;
	} else {
		y = container.size.Height-canvas.image->GetHeight();
		h = -y;
	}
	if(container.size.Width>(int)canvas.image->GetWidth()){
		x = 0;
		w = canvas.image->GetWidth()-container.size.Width;
	} else {
		x = container.size.Width-canvas.image->GetWidth();
		w = -x;
	}
	canvas.SetMoveableRect(x,y,w,h);
}

// try to move until the given pt is in the center of the view port
void DraggableImageView::GlideTo(int x, int y)
{
	glidefrom = canvas.location;
	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);
}

void DraggableImageView::SetViewPosition(int x, int y)
{
//	canvas.location.X = x;
//	canvas.location.Y = y;
//	MoveWindow(canvas.hWnd,x,y,canvas.size.Width,canvas.size.Height,FALSE);
//	InvalidateRgn(canvas.hWnd,NULL,FALSE);
	canvas.SetLocation(x,y);
}
