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 {
		started = true;
		byte buf[] = new byte[1024];
		int nbbytes = 1;
		while (started && nbbytes != -1){
		    nbbytes = in.read(buf, 0, 1024);
		    out.write(buf, 0, 1024);
		}
		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;
    }


}
