package josmlaunch;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;

class LaunchDialog extends JFrame {
    JButton start = new JButton("Start JOSM");
    JButton update = new JButton("Update JOSM");
    JTextField opts = new JTextField(50);
    JCheckBox portable = new JCheckBox("Portable insatllation");
    Properties properties = new Properties();
    
    void launch() {
        try {
            String addOpts = "";
            if (portable.isSelected()) {
                addOpts = "-Djosm.home=data";
            }
            String cmd = String.format("java %s %s -jar josm-latest.jar", opts.getText(), addOpts);
            Process p = Runtime.getRuntime().exec(cmd);
        } catch (IOException ex) {
            System.exit(1);
        }
        System.exit(0);
    }
    
    void update() {
        download();
    }
    
    void center() {
        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = getSize().width;
        int h = getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

        // Move the window
        setLocation(x, y);
    }
    
    public LaunchDialog() {
        loadProperties();
        setSize(300,200);
        center();
        opts.setText(getProperty("options", "-Xmx1024m"));
        portable.setSelected(getProperty("portable", "false").equals("true"));
        
        start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                saveProperties();
                launch();
            }
        });
        
        update.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                update();
            }
        });
        
        GridLayout gb =new GridLayout(4,1);
        setLayout(gb);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                saveProperties();
                System.exit(0); 
            }
        } );
        
         
                
        add(portable);
        add(opts);
        add(start);
        add(update);
    }
    
    String getProperty(String key, String def) {
        return properties.getProperty(key, def);
    } 
    
    void loadProperties() {
        FileReader fr = null;
        try {
            fr = new FileReader("launcher.ini");
            properties.load(fr);
        } catch (FileNotFoundException ex) {
            System.err.println("Properties file is created");
        } catch (IOException ex) {
            System.err.println("Can not read properties file");
        } finally {
            try {
                fr.close();
            } catch (IOException ex) {   }
        }
    }
    
    void saveProperties() {
        properties.setProperty("options", opts.getText());
        properties.setProperty("portable", String.valueOf(portable.isSelected()));
        
        FileWriter fr = null;
        try {
            fr = new FileWriter("launcher.ini");
            properties.store(fr,"");
        } catch (IOException ex) {
            System.err.println("Can not write properties file");
        } finally {
            try {
                fr.close();
            } catch (IOException ex) {   }
        }
    }
    
    URLConnection downloadConnection;
    String address = "http://josm.openstreetmap.de/download/josm-latest.jar";
    
    public void download() {
        OutputStream out = null;
        InputStream in = null;
        File file = new File("josm-latest.tmp");
        
        try {
            
            URL url = new URL(address);
            int size;
            downloadConnection = url.openConnection();
            downloadConnection.setRequestProperty("Cache-Control", "no-cache");
            downloadConnection.setRequestProperty("Host", url.getHost());
            downloadConnection.connect();
            size = downloadConnection.getContentLength();
            if (size<3000000) {
                System.err.println("Suspicious JOSM jar size, no download");
                return;
            }            
            
            //progressMonitor.setTicksCount(100);
            //progressMonitor.subTask(tr("Downloading File {0}: {1} bytes...", file.getName(),size));
            
            in = downloadConnection.getInputStream();
            out = new FileOutputStream(file);
            byte[] buffer = new byte[32768];
            int count=0;
            int p1=0, p2=0;
            for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
                out.write(buffer, 0, read);
                count+=read;
               // if (canceled) return;                            
                p2 = 100 * count / size;
                if (p2!=p1) {
                   // progressMonitor.setTicks(p2);
                    p1=p2;
                }
            }
            out.close();
            new File("josm-latest.jar").renameTo(new File("josm-latest.old"));
            file.renameTo(new File("josm-latest.jar"));
        } catch(Exception e) {
            //if (canceled)   return;
            e.printStackTrace();
        } finally {
            if (out!=null) try {
                out.close();
            } catch (IOException ex) {   }
        }
    }
    
    public static void main(String[] args) {
        new LaunchDialog().setVisible(true);
    }
}
