package org.ourfilesystem.test.ui.db;

/*
OurFileSystem is a peer2peer file sharing program.
Copyright (C) 2012  Robert Gass

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

import static org.junit.Assert.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.junit.Test;
import org.ourfilesystem.filehander.FileSplitter;
import org.ourfilesystem.utilities.FileUtils;

public class FileSplitterTest {
	
	@Test
	public void test() {		
		try {
			
			Random r = new Random();
			
			long totalsize = 1024L*1023L;

			File tmpdir = new File("tmpdir99");
			if (tmpdir.exists()) {
				if (!tmpdir.isDirectory()) {
					fail();
				}
			}
			else {
				tmpdir.mkdirs();
			}
			
			File startfile = File.createTempFile("startfile", ".dat", tmpdir);
			System.out.println("Starting file: " + startfile);
			
			FileOutputStream fos = new FileOutputStream(startfile);
			byte b[] = new byte[1024];
			long pos = 0;
			while (pos < totalsize) {
				r.nextBytes(b);
				int ws = Math.min((int)(totalsize-pos), 1024);
				fos.write(b, 0, ws);
				pos += ws;
			}
			fos.close();
			
			
			long splitsize = 23L*1024L;
			List<File> flist = FileSplitter.split(startfile, tmpdir, splitsize);
			
			int expected = (int) (totalsize/splitsize);
			if ((totalsize % splitsize) != 0) expected++;
			
			assertEquals(flist.size(), expected);
			
			Iterator<File> i = flist.iterator();
			while (i.hasNext()) {
				File f = i.next();
				if (f.length() > (splitsize + (2*(Long.SIZE/Byte.SIZE)))) {
					System.out.println("fsize: " + f.length() + " splitsize: " + splitsize);
					fail();
				}
			}
			
			
			File outfile = File.createTempFile("endfile", ".dat", tmpdir);
			for (int cnt = flist.size()-1; cnt >= 0; cnt--) {
				System.out.println(" + " + flist.get(cnt));
				FileSplitter.insert(outfile, flist.get(cnt));
			}
			
			
			System.out.println("diff: " + startfile + " <> " + outfile);
			assertTrue(FileUtils.diff(startfile, outfile));
			
			
		} catch (IOException e) {
			e.printStackTrace();
			fail();
		}
		
	}

}
