package de.lazyzero.NazeWiiConf.utils;

import static lu.tudor.santec.i18n.Translatrix._;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;

import de.lazyzero.NazeWiiConf.NazeWiiConf;
import de.lazyzero.NazeWiiConf.gui.NazeUploadPanel;

public class STMLoader {
	
	private NazeWiiConf instance;
	private ProgressListener progressListner;
	private NazeWiiLogger logger;
	private int count;
	private int errorcount;

	public STMLoader(NazeWiiConf instance, ProgressListener progressListener) {
		this.instance = instance;
		this.progressListner = progressListener;
		
		logger = instance.getLogger();
	}
	
public void flashFirmware(Firmware revision) throws IOException {
		
		Vector<String> cmd = new Vector<String>();
		String stmloader = "";
		if (Utils.isMac()) {
			String path = System.getProperty("java.library.path");
        	path = path.substring(0, path.indexOf(":"));
        	stmloader = path + "/lib/stmloader/mac/stmloader";
		} else if (Utils.isLinux()) {
			stmloader = System.getProperty("user.dir")+"/lib/stmloader/linux/stmloader";
		}
		cmd.add(stmloader);
		
		cmd.add("-p");
		cmd.add(instance.getPort());
		
		cmd.add("-b");
		cmd.add(instance.getBuadrate()+"");
		
		cmd.add("-f");
		cmd.add(Utils.getTempFolder()+"/baseflight_r" + revision.getRevision() + ".hex");
		
//		./stmloader -p /dev/cu.SLAB_USBtoUART -b115200 -f /Users/moll/Library/Preferences/NazeWiiConf/baseflight_r166.hex 

		String [] cmdArray = new String [cmd.size()];
        cmd.toArray(cmdArray);
		
		final Process p = Runtime.getRuntime().exec(cmdArray);
        new Thread() {
        	public void run() {
        		
        		int line;
        		BufferedInputStream bis =  new BufferedInputStream(p.getErrorStream());
        		
        		try {
					while ((line = bis.read()) != -1) {
//						logger.log(Level.INFO, ((char)line)+"");
//						m_intfTextOutput.print(((char)line)+"");
						System.err.print((char)line);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        }.start();
        
        count = 0;
        errorcount = 0;
        new Thread() {
        	public void run() {
        		((NazeUploadPanel)progressListner).getUploadButton().setEnabled(false);
        		
        		int line;
        		BufferedInputStream bis =  new BufferedInputStream(p.getInputStream());
        		
        		try {
					while ((line = bis.read()) != -1) {
//						logger.log(Level.INFO, ((char)line)+"");
						System.out.print((char)line);
						if (((char)line) == '=') {
							count++;
							if (count == 35) {
								progressListner.updateProgressBy(1);
								count = 0;
							}
						} else if (((char)line) == 'p') {
							errorcount++;
							if (errorcount == 20) {
								logger.log(Level.WARNING, _("nazeUploadPanel.flashFailedDevice"), true);
								break;
							}
						}
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        	}
        }.start();
        try {
			p.waitFor();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println("exit: "+p.exitValue());
        if (p.exitValue() == 0){
        	System.out.println("===: "+count);
        	logger.log(Level.INFO, _("firmwarePanel.uploadFinished"), true);
        	progressListner.updateProgress(100);
        	((NazeUploadPanel)progressListner).getRefreshButton().setEnabled(true);
        	((NazeUploadPanel)progressListner).getUploadButton().setEnabled(true);
        	
        } else {
        	logger.log(Level.WARNING, _("nazeUploadPanel.flashFeiled"), true);
        }
	}

}
