package blocks;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;

import main.Core;
import main.Utils;
import net.FileListener;
import peer.Peer;

/**
 * Accepts blocks confirmed to be needed
 * @author caik
 *
 */
public class BlockAcceptor implements Runnable {
	
	private Peer peer;
	private String forFile;
	private String blockName;
	private CountDownLatch fsLatch;
	

	public BlockAcceptor(Peer peer, String forFile, String blockName) {
		this.peer = peer;
		this.forFile = forFile;
		this.blockName = blockName;
	}
	
	public void run() {
		try {
			fsLatch = new CountDownLatch(1);
			FileListener ssm = new FileListener(fsLatch);
			Thread serverSocketMakerThread = new Thread(ssm);
			serverSocketMakerThread.setName("Server Socket Maker Thread");
			serverSocketMakerThread.start();
			fsLatch.await();
			System.out.println("File server socket connected with incoming");
			Socket newFS = ssm.getRes();
			peer.setFS(newFS);
			
			DataInputStream dis = new DataInputStream(peer.fs.getInputStream());
			FileOutputStream fos = new FileOutputStream(Utils.defineAppDataDir() 
														+ "/" 
														+ (forFile) //(already base64'd)
														+ "/" + blockName + ".dat", false);
			byte[] buffer = new byte[(int) Core.chunkSize];
			int read = 0;
			while((read = dis.read(buffer)) > 0) {
				fos.write(buffer, 0, read);
			}
			fos.close();
			dis.close();
			peer.fs.close();
			Core.mainWindow.out("File transfer of block " + blockName + " for " + forFile + " complete.");
			Utils.print(this, "Got block successfully");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

@@ -631,16 +631,75 @@
 %09%09try %7B%0A
+%09%09%09FileListener ssm;%0A%09%09%09if(Core.firstBlockServerSocket) %7B%0A%09
 %09%09%09fsLat
@@ -729,29 +729,17 @@
 (1);%0A%09%09%09
+%09
-FileListener 
 ssm = ne
@@ -763,16 +763,17 @@
 Latch);%0A
+%09
 %09%09%09Threa
@@ -817,16 +817,17 @@
 d(ssm);%0A
+%09
 %09%09%09serve
@@ -887,16 +887,17 @@
 d%22);%0A%09%09%09
+%09
 serverSo
@@ -924,16 +924,17 @@
 t();%0A%09%09%09
+%09
 fsLatch.
@@ -942,16 +942,37 @@
 wait();%0A
+%09%09%09%09Core.ssm = ssm;%0A%09
 %09%09%09Syste
@@ -1009,31 +1009,150 @@
 ket 
-connected with incoming
+generated%22);%0A%09%09%09%09Core.firstBlockServerSocket = false;%0A%09%09%09%7D else %7B%0A%09%09%09%09ssm = Core.ssm;%0A%09%09%09%7D%0A%09%09%09System.out.println(%22File server socket connected
 %22);%0A
@@ -1422,16 +1422,16 @@
 se64'd)%0A
+
 %09%09%09%09%09%09%09%09
@@ -1457,17 +1457,8 @@
 Name
- + %22.dat%22
 , fa

Allow BlockAcceptor to reuse ServerSocket