package Updater;
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
public class UpdateConnector extends Thread {
	
	private String url_to_down = null;
	private String file_name = null;
	private long file_len = 0;
	private static String windir = System.getProperty("user.home");
	private static String path = System.getProperty("path.separator"); 
	private FileOutputStream fos;
	private File file;
	private UpdatePanel up;
	
	//Update etmemiz icin gerekecek olan constructor!
	public UpdateConnector(UpdatePanel up,String url_to_down,String file_name,
		long file_len) {
		this.url_to_down = url_to_down;
		this.file_name = file_name;
		this.file_len = file_len;
		this.up = up;
		file = new File(windir+path+file_name);
		if(!file.exists() || file.length() != file_len) {
			start();
		} else {
			//JOptionPane.showMessageDialog(null,"You have already installed the last service packet.","KBD Report",JOptionPane.PLAIN_MESSAGE);
			up.setProgramMode(UpdatePanel.RESULT_MODE);
			up.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
			up.repaint();
		}
	}
	//fos,url,up bolumu ve kanal
	public void run() {
		try {
			fos = new FileOutputStream(file);
			URL url = new URL(url_to_down);
			URLConnection uc = url.openConnection();
			uc.setUseCaches(false);
			uc.setDefaultUseCaches(false);
			uc.setAllowUserInteraction(false); 
			InputStream is = uc.getInputStream();
			byte byt[] = new byte[2048];
			int len = 0;
			while((len = is.read(byt)) != -1) {
				fos.write(byt,0,len);
				fos.flush();
			}
			try {
				fos.close();
				is.close();
			} catch(Exception e) {
					up.setProgramMode(UpdatePanel.RESULT_MODE);
					up.setResultMessage("Installation complete but could not close the file!");
					up.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
					up.repaint();
			}
			
			//JOptionPane.showMessageDialog(null,"New Components Arrived!","KBD Report",JOptionPane.PLAIN_MESSAGE);
			up.setResultMessage("Installation complete!...");
			up.setProgramMode(UpdatePanel.RESULT_MODE);
			up.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		} catch(Exception e) {
			up.setProgramMode(UpdatePanel.RESULT_MODE);
			up.setResultMessage("Error while downloading file");
			up.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
			up.repaint();
		}
	}
}