package com.beem.project.beem.jingle;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class FileSender extends Thread {

    public static void main(String args[]) throws InterruptedException, UnknownHostException {
	FileSender fs = new FileSender("127.0.0.1", 4242, "/tmp/img.jpeg");
	fs.start();
	fs.join();
    }

    private int         port;
    private boolean     started = false;
    private String      filename;

    private InetAddress local_addr;

    public FileSender(String listenAddr, int port, String file) throws UnknownHostException {
	this.port = port;
	this.filename = file;
	this.local_addr = InetAddress.getByName(listenAddr);
    }

    @Override
    public void run() {
	try {
	    ServerSocket ssock = new ServerSocket(port, 50, local_addr);
	    InputStream in = new BufferedInputStream(new FileInputStream(filename));
	    Socket sock = ssock.accept();
	    OutputStream out = new BufferedOutputStream(sock.getOutputStream());

	    try {
		// peut etre se debarasser de started
		started = true;
		byte buf[] = new byte[1024];
		int nbbytes = 1;
		while (started) {
		    nbbytes = in.read(buf, 0, 1024);
		    if (nbbytes == -1)
			break;
		    out.write(buf, 0, nbbytes);
		}
		started = false;
	    } finally {
		if (in != null)
		    in.close();
		if (out != null)
		    out.close();
		if (sock != null)
		    sock.close();
		if (ssock != null)
		    ssock.close();
	    }
	} catch (FileNotFoundException e) {
	    System.err.println("Impossible d'ouvrir " + filename + " " + e.getLocalizedMessage());
	} catch (IOException e) {
	    System.err.println("I/O Error " + e.getLocalizedMessage());
	}
    }

    public void setStarted() {
	started = false;
    }

}
