package vut.msa.transport;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import javax.net.ssl.SSLSocket;
import org.apache.log4j.Logger;

public class FileStreamer {

    private static final Logger log = Logger.getLogger(FileStreamer.class);
    private SSLSocket socket;

    public FileStreamer(SSLSocket socket) throws IOException {
        this.socket = socket;
    }

    public void sendFile(File file) throws IOException {

        log.info("Starting file transfer: " + file.getName());

        int completed = 0;
        byte[] mybytearray = new byte[socket.getSendBufferSize()];

        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = socket.getOutputStream();
        CheckedOutputStream cos = new
                CheckedOutputStream(os, new Adler32());
        log.info("Streams ready, starting transfer.");
        while ((completed = bis.read(mybytearray)) != -1) {
            cos.write(mybytearray, 0, completed);
        }
        
        os.flush();
        log.info("Subor odoslany. Checksum suboru: " + cos.getChecksum().getValue());
    }

    public void readFile(File file) throws IOException {

        log.info("Zacinam prijimat subor.");

        int bytesRead;

        InputStream is = socket.getInputStream();
        CheckedInputStream cis = new
                CheckedInputStream(is, new Adler32());
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] buffer = new byte[socket.getReceiveBufferSize()];
        
        while ((bytesRead = cis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        bos.flush();

        bos.close();
        fos.close();

        log.info("Subor nacitany. Checksum suboru: " + cis.getChecksum().getValue());
    }
}
