package de.lazyzero.kkMulticopterFlashTool.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;

import de.lazyzero.kkMulticopterFlashTool.KKMulticopterFlashTool;

public class Firmware {

	private File file;
	private String version;
	private String author;
	private String name;
	private String controller;
	private URL url;
	private String md5Calculated;
	private String md5;
	private URL zipURL;
	
	public Firmware(){}

	public Firmware(File firmwareFile) {
		this.file = firmwareFile;
		System.out.println(this.getFile().getAbsolutePath());
	}

	public Firmware(URL firmwareURL) throws NullPointerException{
		if (firmwareURL!=null){
			this.url = firmwareURL;
		}

	}
	
	public URL getFileURL() {
		return url;
	}
	
	public URL getZipURL() {
		return zipURL;
	}

	public File getFile() {
		if (KKMulticopterFlashTool.isOfflineMode()) {
			if (zipURL != null) {
				String filename = null;
				String tmpdir = null;
				
				String urlPath = url.getPath();
				filename = urlPath.substring(urlPath.lastIndexOf("/")+1);
				System.out.println("Download file: "+filename);
				
		        tmpdir = KKMulticopterFlashTool.getTempFolder();
		        	
				File tmpFile = new File(tmpdir + filename);
				File fExtract = new File(url.toString().substring(7).trim());
				this.file = Zip.unzip(tmpFile, fExtract);
				this.md5Calculated = MD5.getMD5(file);
			} else if (url != null) {
				String filename = null;
				String tmpdir = null;
				
				String urlPath = url.getPath();
				filename = urlPath.substring(urlPath.lastIndexOf("/")+1);
				System.out.println("Load file from temp folder: "+filename);
				
		        tmpdir = KKMulticopterFlashTool.getTempFolder();
		        	
				this.file = new File(tmpdir + filename);
				this.md5Calculated = MD5.getMD5(file);
				System.out.println(md5Calculated);
			}
		} else { // this condition is for downloading the files
			if (zipURL != null) {
				File f = this.downloadFile(zipURL);
				File fExtract = new File(url.toString().substring(7).trim());
				this.file = Zip.unzip(f, fExtract);
				this.md5Calculated = MD5.getMD5(file);
			} else if (url != null) {
				this.file=downloadFirmware(url);
				this.md5Calculated = MD5.getMD5(file);
				System.out.println(md5Calculated);
			}
		}
		
		//check the md5
		return file;
	}

	private File downloadFile(URL url){
		String filename = null;
		String tmpdir = null;
		
		String urlPath = url.getPath();
		filename = urlPath.substring(urlPath.lastIndexOf("/")+1);
		System.out.println("Download file: "+filename);
		
        tmpdir = KKMulticopterFlashTool.getTempFolder();
        filename = tmpdir + filename;
        	
		File tmpFile = new File(filename);
		if ((new File(tmpdir)).mkdir()) System.out.println("tmpdir created");
		
		if (!tmpFile.exists()) {
    		try {
    			
    			BufferedInputStream in = new BufferedInputStream(url.openStream());
    			FileOutputStream fos = new FileOutputStream(tmpFile);
    			BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
    			byte[] data = new byte[1024];
    			int x=0;
    			while((x=in.read(data,0,1024))>=0) {
    				bout.write(data,0,x);
    			}
    			bout.close();
    			in.close();
    		} catch (FileNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
		} else {
			System.out.println("skip download. File already loaded.");
		}

		System.out.println("Download finished: " + filename);
		return tmpFile;
	}
	
	private File downloadFirmware(URL firmwareURL){
		String filename, tmpdir;
		
		String urlPath = firmwareURL.getPath();
		filename = urlPath.substring(urlPath.lastIndexOf("/")+1);
		System.out.println("Download file: "+filename);
		
        tmpdir = KKMulticopterFlashTool.getTempFolder();
        filename = tmpdir+filename;
		
		File tmpFile = new File(filename);
		if ((new File(tmpdir)).mkdir()) System.out.println("tmpdir created");
		
		if (!tmpFile.exists()){
			try {
				BufferedInputStream in = new BufferedInputStream(firmwareURL.openStream());
				FileOutputStream fos = new FileOutputStream(tmpFile);
				BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
				byte[] data = new byte[1024];
				int x=0;
				while((x=in.read(data,0,1024))>=0) {
					bout.write(data,0,x);
				}
				bout.close();
				in.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			System.out.println("skip download. File already loaded.");
		}

		System.out.println("Download finished: " + filename);
		return tmpFile;
	}
	
	public String toString() {
		return name + " ( V" + version + " [" + controller + "]" + " " + author + " )";
	}
	
	public String toString2() {
		return name+version+author;
	}
	
	public String getController() {
		return controller;
	}

	/**
	 * @param version the version to set
	 */
	public void setVersion(String version) {
		this.version = version;
	}

	/**
	 * @param author the author to set
	 */
	public void setAuthor(String author) {
		this.author = author;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	public String getName() {
		return name;
	}

	/**
	 * @param controller the controller to set
	 */
	public void setController(String controller) {
		this.controller = controller;
	}
	
	public void setMD5(String md5) {
		this.md5 = md5; 
	}

	public void setZipURL(URL zipurl) {
		this.zipURL = zipurl;
	}
	
	public static void main(String[] args) {
		Firmware f = null;
		
		try {
			f = new Firmware();
			File ff = f.downloadFirmware(new URL("http://www.kkmulticopter.kr/multicopter/firmware/XXcontrol_KR_DualCopter_v1_5.hex"));
			MD5.getMD5(ff);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		try {
//			f = new Firmware(new URL("http://www.lazyzero.de/_media/firmware.hex"));
//			f.setAuthor("ich");
//			f.setController("m48");
//			f.setName("Quad");
//			f.setVersion("0.3");
//		} catch (NullPointerException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (MalformedURLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		f.getFile();
		//f.downloadFirmware(f.url);
	}

	public static Vector<Firmware> getOfflineAvailableFirmwares(Vector<Firmware> inputFirmwares) {
		Vector<Firmware> firmwares = new Vector<Firmware>();
		String tmpFolder = KKMulticopterFlashTool.getTempFolder();
		
		for (Firmware firmware : inputFirmwares) {
			
			if (firmware.zipURL != null) {
				String urlPath = firmware.zipURL.getPath();
				String filename = urlPath.substring(urlPath.lastIndexOf("/")+1);
				if (new File(tmpFolder+filename).exists()) {
					firmwares.add(firmware);
				}
			} else if (firmware.url != null) {
				String urlPath = firmware.url.getPath();
				String filename = urlPath.substring(urlPath.lastIndexOf("/")+1);
				if (new File(tmpFolder+filename).exists()) {
					firmwares.add(firmware);
				}
			}
		}
		
		
		return firmwares;
	}

	

	

	
}
