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.Socket;

public class FileSender extends Thread {
    private String dest;
    private int port;
    private boolean started = false;
    private String filename;

    public FileSender(String dest, int port, String file){
	this.dest = dest;
	this.port = port;
	this.filename = file;
    }

    public void run(){
	try {
	    InputStream in = new BufferedInputStream(new FileInputStream(filename));
	    Socket sock = new Socket(dest, port);
	    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();
	    }
	} catch (FileNotFoundException e){
	    System.err.println("Impossible d'ouvrir " + filename +" " + e.getLocalizedMessage());
	} catch (IOException e) {
	    System.err.println("Imposible de se connecter a " + dest + " " + e.getLocalizedMessage());
	}
    }

    public void setStarted(){
	started = false;
    }

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

}
