/*	Table widget for FLTK-2
	Test application
	Copyright(C) 2007 Alex Ivanov
	http://www.aleksoft.net
*/

#include "Table.H"
#include <fltk/Font.h>
#include <fltk/ask.h>
#include <vector>
#include <string>

struct  mydata {uint R;uint C;std::string data;};
std::vector<mydata> dt;

class Editor : public Input
{
public:
	Editor(int x, int y, int w, int h, uint r, uint c) : Input(x, y, w, h)
	{
		r_ = r; c_ =c;
		value(getdata(r,c));
	};
	~Editor()
	{
		setdata();
	}
	static const char* getdata(uint R,uint C)
	{
		mydata el;
		for(uint i=0;i<dt.size();i++)
		{
			el = dt.at(i);
			if(el.R == R && el.C == C)
			{//printf("getdata: %d %d %s\n",R,C,el.data.c_str());
				return el.data.c_str();
			}
		}
		char buf[30];
		sprintf(buf,"R=%d, C=%d",R,C);
		el.data = buf;
		return el.data.c_str();			
	}
	static void showEditor(Table& t,uint R,uint C,Widget** editor)
	{
		Editor* edt=(Editor*)*editor;
		if(edt) 
		{
			t.remove(edt);
			delete edt;
		}
		edt=new Editor(t.colOffset(C),t.rowOffset(R),t.colWidth(C),t.rowHeight(R),R,C);
		t.add(edt);
		*editor = edt;
		edt->value(Editor::getdata(R,C));
		edt->show();
		edt->take_focus();
	}

private:
	uint r_; uint c_;
	void setdata()
	{
		mydata el;
		if(getdata(r_,c_) != value())
		{
			for(uint i=0;i<dt.size();i++)
			{
				el = dt.at(i);
				if(el.R == r_ && el.C == c_)
				{
					el.data=value();
					dt.at(i)=el;
					return;
				}
			}
			el.R=r_; el.C=c_; el.data=value();
			dt.push_back(el);
		}	
	}
};



void drawCell(Table& t,int R,int C) 
{
	Rectangle rect(t.colOffset(C), t.rowOffset(R) ,t.colWidth(C),t.rowHeight(R));
	push_clip(rect);
	setcolor(GRAY50);
	fillrect(rect);
	rect.w(rect.w()-1);
	rect.h(rect.h()-1);
	if(t.selectedRow == R) 
		setcolor(t.selection_color());
	else
	{
		if(R < 0 || C <0)
		{
			setcolor(GRAY75);
			setfont(getfont()->plus(BOLD),getsize());
		}
		else
		{
			setcolor(WHITE);
			setfont(t.textfont(),getsize());
		}
	}
	fillrect(rect);
	//push_clip(rect);
	rect.x(rect.x()+5);
	rect.w(rect.w()-5);
	if(t.selectedRow == R) 
		setcolor(t.selection_textcolor());
	else
		setcolor(t.textcolor());
	drawtext(Editor::getdata(R,C),rect,ALIGN_LEFT | ALIGN_TOP);
	pop_clip();
};

int main(int argc, char** argv) {
	Window win(600,400);
	win.box(THIN_DOWN_BOX);
	win.begin();
	Widget l(win.w()/2 - 100,4,200,16,"Double click a cell to edit");
	l.box(NO_BOX);
	l.align(ALIGN_CENTER);
	Table test(20,20,550,350,1000000,5,16,100);
	test.colWidth(-2,150);
	test.colWidth(0,100);
	test.rowHeight(-2,100);
	test.type(ScrollGroup::BOTH);
	test.setFixedRows(COLHEADER | ROWHEADER);
	test.showEditor = Editor::showEditor;
	test.drawCell=drawCell;
	win.resizable(win);
	win.end();
	win.show(argc,argv);
	return run();
}
