/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.greinet.tvtotalripper.download;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * @author agreiner
 */
public class ConnectionUtil {
    
    /**  The connection to the download URL */
    private HttpURLConnection httpConn;
    /** The input stream from the connection */
    private InputStream inputStream;
    /** The download size */
    private int contentLength;
    
    /**
     * Prepare the download connection and open the input stream
     * @param fileUrl the URL to the file
     * @throws IOException error preparing download
     */
    public void prepare(String fileUrl) throws IOException{
        URL url = new URL(fileUrl);
        httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
        
        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            contentLength = httpConn.getContentLength();
            // opens input stream from the HTTP connection
            inputStream = httpConn.getInputStream();
 
        } else {
            throw new IOException(
                    "No file to download. Server replied HTTP code: "
                            + responseCode);
        }
    }
    
    /**
     * Close the inout stream and disconnect the download
     * @throws IOException 
     */
    public void disconnect() throws IOException {
        inputStream.close();
        httpConn.disconnect();
    }
 
    /**
     * Get the content length of the download
     * @return the content length
     */
    public int getContentLength() {
        return this.contentLength;
    }
 
    /**
     * Get the download related inout stream
     * @return the input stream 
     */
    public InputStream getInputStream() {
        return this.inputStream;
    }
    
}
