

#include <stdio.h>
#include "glut.h"
#include "timetext.h"



TimeText::TimeText() : numitems(0) , maxitems(0) { }

TimeText::TimeText(int sx, int sy, int xs, int ys) : Visualization(sx,sy,xs,ys), numitems(0) { 
	maxitems = ys / 12;
}

void TimeText::Draw() {
	int i;

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(startx,startx+xsize,starty,starty+ysize);
			// left, right, bottom, top
	glViewport(startx, starty, xsize, ysize);
			// startx, starty, xsize, ysize
			// coordinates begin from lower left corner of window
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
    glDisable(GL_TEXTURE_2D);
	glDisable(GL_LIGHTING);

	glLineWidth(1);
	glColor3f(0.1,0.1,0.1);
	glBegin(GL_LINES);
	glVertex3f((float)startx,(float)starty,0.0);
	glVertex3f((float)startx,(float)starty+(float)ysize,0.0);
	glEnd();

	if (numitems<maxitems) {
		for (i=0;i<numitems;i++) {
			glColor4f(colors[i][0],colors[i][1],colors[i][2],colors[i][3]);
			//glRasterPos3f((float)startx+20,(float)starty+(float)i/(float)maxitems*(float)ysize,0.0);
			glRasterPos3f((float)startx+20,ycoords[i],0.0);
			NT.font.Render(texts[i]);
			glBegin(GL_LINES);
			//glVertex3f((float)startx+20,(float)starty+(float)i/(float)maxitems*(float)ysize,0.0);
			glVertex3f((float)startx+20,ycoords[i],0.0);
			glVertex3f((float)startx,(float)starty+(float)(times[i]-mintime)/(float)(maxtime-mintime) * (float)ysize,0.0);
			glEnd();
		}
	}

}

// set ycoords
void TimeText::Arrange() {

	int i;
	int pos[512];
	int min_pos, max_pos, ideal_pos;
	int finished;
	int off;

	if (numitems > maxitems) {
		//for (i=0;i<numitems;i++) {
		//	ycoords[i] = (float)starty+(float)i/(float)numitems * (float)ysize;
		//}
	} else {
		// step 1: put all the entries in the middle
		off = (maxitems - numitems) / 2;
		for (i=0;i<numitems;i++) {
			pos[i] = i+off;
		}
		// step 2: from the top, move items up
		
		min_pos = 0;
		finished = 0;
		for (i=0;((i<numitems)&&(finished==0));i++) {
			ideal_pos = (int)((float)(times[i]-mintime)/(float)(maxtime-mintime) * (float)maxitems);
			if (pos[i] > ideal_pos) {
				if (ideal_pos >= min_pos) {
					pos[i] = ideal_pos;
					min_pos = ideal_pos + 1;
				} else if (pos[i] > min_pos) {
					pos[i] = min_pos;
					min_pos++;
				} else {
					finished = 1;
				}
			} else {
				finished = 1;
			}
		}
		
		// step 3: from the bottom, move items down

		max_pos = maxitems-1;
		finished = 0;
		for (i=numitems-1;((i>=0)&&(finished==0));i--) {
			ideal_pos = (int)((float)(times[i]-mintime)/(float)(maxtime-mintime) * (float)maxitems);
			if (pos[i] < ideal_pos) {
				if (ideal_pos <= max_pos) {
					pos[i] = ideal_pos;
					max_pos = ideal_pos - 1;
				} else if (pos[i] < max_pos) {
					pos[i] = max_pos;
					max_pos--;
				} else {
					finished = 1;
				}
			} else {
				finished = 1;
			}
		}



		// step 4: convert from position index to coords
		for (i=0;i<numitems;i++) {
			ycoords[i] = (float)starty+(float)(pos[i])/(float)maxitems * (float)ysize;
		}
	}

}







