import std.string;
import dom;
import filedb;
import binload;

class XMLFileDB
{
	private char[] filename;
	private int tablesize;
	this(char[] filename,int tablesize){
		this.filename = filename;
		this.tablesize = tablesize;
	}
	bool add(Dom d){
		char[] data = BinPack.pack(d);
		return FileDB.addDBFile(filename, tablesize,data);
	}
	Dom[] read(int offset,int size){
		Dom[] array;
		char[][] data = FileDB.readDBFile(filename,offset,size);
		for(int i=0;i<data.length;i++){
			if(data[i].length==0){
				array ~= null;
				continue;
			}
			array ~= BinUnpack.unpack(data[i]);
		}
		return array;
	}
	int getSize()
	{
		return FileDB.readSize(filename);
	}
	bool remove(int offset){
		return FileDB.removeDBFile(filename,offset);
	}
}
version(XMLFILEDB_TEST){
void main()
{
	printf("content-type: text/html;charset=SHIFT_JIS\n\n");
	XMLFileDB db = new XMLFileDB("xmlfiledb.bin",256);
	char[]tmplstr = cast(char[])read("xmlfiledb.xml");
	Dom tmpl = Dom.parse(tmplstr).getDocument();
	int size = db.getSize();
	Dom d[] = db.read(0,size);
	int viewsize=5;
	int start = size-viewsize;
	if(start<0)start=0;
	for(int j=0;j<tmpl.array.length;j++){
		if(tmpl.array[j].type==Dom.CDATA){
			printf("%.*s",tmpl.array[j].value);
		}else
		if(tmpl.array[j].value=="bord"){
			for(int i=start;i<size;i++){
				if(d[i]!==null){
					Dom dom = d[i].getDocument();
					Dom bord = tmpl.array[j];
					for(int k=0;k<bord.array.length;k++){
						if(bord.array[k].type==Dom.CDATA){
							printf("%.*s",bord.array[k].value);
						}else
						if(bord.array[k].value=="title"){
							printf("%.*s",dom.getAttr("title"));
						}else
						if(bord.array[k].value=="name"){
							printf("%.*s",dom.getAttr("name"));
						}else
						if(bord.array[k].value=="email"){
							printf("%.*s",dom.getAttr("email"));
						}else
						if(bord.array[k].value=="passwd"){
							printf("%.*s",dom.getAttr("passwd"));
						}else
						if(bord.array[k].value=="contents"){
							printf("%.*s",dom.array[0].toString());
						}
					}
				}
			}
		}
	}
	for(int i=0;i<33;i++){
		int size = db.getSize();
		Dom dom = newDom(Dom.BLOCK,"bbs")
			.setAttr("name","sakurai")
			.setAttr("email","sakurai@ma.mni.ne.jp")
			.setAttr("title","title"~std.string.toString(size))
			.setAttr("passwd","pass")
			.add(newDom(Dom.TEXT,`naiyo!`~std.string.toString(size*243245)))
		;
		bool rc = db.add(dom);
		//printf("delete %d rc=%d\n",size-10,db.remove(size-10));
	}
}
}
