package adecWatt.control;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import misc.Bundle;
import misc.Config;
import misc.RemoteUpdate;

import adecWatt.model.AdecWatt;
import adecWatt.view.JProp;

public class LaunchAdecWatt {

    // ========================================
    static public void main (String[] args) {
	try {
	    Config.setPWD (LaunchAdecWatt.class);
	    Config.load ("AdecWatt");
	    Bundle.load ("Help");
	    Bundle.load ("ToolBar");
	    Bundle.load ("Proxy");
	    Bundle.load ("RemoteUpdate");
	    Bundle.load ("Story");
	    Bundle.load ("Controller");
	    Bundle.load ("AdecWatt");
	    Bundle.load (JProp.AdecWattUser);

	    updateShell ();

	    final AdecWatt adecWatt = new AdecWatt ();
	    SwingUtilities.invokeLater (new Runnable () {
		    public void run () {
			AdecWattController adecWattController = new AdecWattController (adecWatt);
			adecWatt.broadcastDisplay ("Console", Bundle.getMessage ("Welcome"));
			adecWattController.updateUserChangeProfil ();
		    }
		});
	} catch (Exception e) {
	    File softDir = new File (Config.getPWD ().getParentFile (), "soft");
	    File jar = new File (softDir, "UpdatedAdecWatt.jar");
	    RemoteUpdate.launch (jar);
	}
    }

    public static void updateShell () {
	try {
	    File dir = Config.getPWD ().getParentFile ();
	    File oldLaunch = new File (dir, "launch-lightPlot.sh");
	    File softDir = new File (dir, "soft");
	    File newJar = new File (softDir, "AdecWatt.jar");
	    File oldJar = new File (softDir, "LightPlot.jar");
	    if (newJar.length () < 1024)
		return;
	    if (oldLaunch.length () > 70) {
		PrintWriter pw = new PrintWriter (oldLaunch);
		pw.println ("#!/bin/bash");
		pw.println ("cd `dirname \"$0\"`");
		pw.println ("java -jar soft/AdecWatt.jar");
		pw.flush ();
		pw.close ();
		JOptionPane.showMessageDialog (null,
					       "Votre logiciel a \u00E9t\u00E9 mis \u00E0 jour.\n"+
					       "Vous devez relancer l'application\n", "Information", JOptionPane.ERROR_MESSAGE);
		System.exit (0);
	    }
	    if (oldJar.exists ())
		oldJar.delete ();
	} catch (FileNotFoundException e) {
	}
    }

    // ========================================
}
