#include "kfilehdr.h"
#include <qpaintd.h>
#include <qdrawutil.h>
#include <iostream.h>
#include <kapp.h>

KFileHeader::KFileHeader(QWidget *parent, const char *name, WFlags f)
	: QWidget(parent,name,f)
{
	setBackgroundMode(NoBackground);
	setMouseTracking(TRUE);
/*	Names[0] = i18n("Name"); ColWidth[0] = 150;	
	Names[1] = i18n("Size"); ColWidth[1] = 100;	
	Names[2] = i18n("File Type"); ColWidth[2] = 150;	
	Names[3] = i18n("Modified"); ColWidth[3] = 200;	
	Names[4] = i18n("Permissions"); ColWidth[4] = 150;*/
	isPressed[0] = isPressed[1] = isPressed[2] = isPressed[3] = isPressed[4] = FALSE;
	dx = 0;
	Resizing = FALSE;
	ColResized = 0;
}

KFileHeader::~KFileHeader()
{
}

void KFileHeader::setHScrollValue(int value)
{
	dx = value;
	update();
}

void KFileHeader::paintEvent(QPaintEvent *)
{
	QPixmap		pm(QMAX((int)(width()),(int)(getTotalWidth())+20),height());
	pm.fill(colorGroup().background());
	QPainter	p(&pm);
	uint		pos = 0;
	for (int i=0; i<5; i++) {
		qDrawWinButton(&p,pos,0,ColWidth[i],height(),colorGroup(),isPressed[i]);
		p.setPen(colorGroup().text());
		p.drawText(pos+5,0,ColWidth[i]-6,height(),AlignVCenter,Names[i].data());
		pos += ColWidth[i];
	}
	QPainter	q(this);
	q.drawPixmap(0,0,pm,dx,0,width(),height());
}

void KFileHeader::mousePressEvent(QMouseEvent *e)
{
	if (e->button() == LeftButton) {
		if (cursor().shape() == SizeHorCursor) {
			Resizing = TRUE;
			prev_x = e->x();
		}
		else {
			int	col = 0, pos = 0;
			while ((int)(e->x()+dx) >= pos+ColWidth[col]) pos += ColWidth[col++];
			isPressed[col] = TRUE;
			update();
			emit columnPressed(col);
		}
	}
}

void KFileHeader::mouseReleaseEvent(QMouseEvent *e)
{
	if (e->button() == LeftButton) {
		if (Resizing) Resizing = FALSE;
		else {
//			int	col = 0, pos = 0;
//			while ((int)(e->x()+dx) >= pos+ColWidth[col]) pos += ColWidth[col++];
//			isPressed[col] = FALSE;
			for (int i=0;i<5;i++) isPressed[i] = FALSE;
			update();
		}
	}
}

void KFileHeader::mouseMoveEvent(QMouseEvent *e)
{
	if (!Resizing) {
		int	col = 0, pos = 0;
		while ((int)(e->x()+dx) >= pos+ColWidth[col]-4 && col < 5) pos += ColWidth[col++];
		if (col > 0 && (int)(e->x()+dx) >= pos-5 && (int)(e->x()+dx) <= pos+5) {
			setCursor(sizeHorCursor);
			ColResized = col-1;
		}
		else setCursor(arrowCursor);
	}
	else {
		ColWidth[ColResized] += e->x()-prev_x;
		ColWidth[ColResized] = QMAX(0,ColWidth[ColResized]);
		prev_x = e->x();
		update();
		emit changeColWidth(ColResized,ColWidth[ColResized]);
	}
}

void KFileHeader::setColumns(QStrList& Type, QStrList& Width, QString *Name)
{
	nCol = Type.count();
	QString	num;
	for (int i=0;i<nCol;i++) {
		num = Width.at(i);
		ColWidth[i] = num.toInt();
		ColWidth[i] = QMAX(0,ColWidth[i]);
		num = Type.at(i);
		int	pos = num.toInt();
		if (pos >= 0 && pos < 5) Names[i] = Name[num.toInt()].data();
		else Names[i] = "";
	}
	for (int i=nCol;i<5;i++) {
		Names[i] = "";
		ColWidth[i] = 0;
	}
}
