/*
 * Apocalypse Laboratories
 * Open Source License
 *
 * Source code can be used for any purpose, as long as:
 *  - Compiled binaries are rebranded and trademarks are not
 *    visible by the end user at any time, except to give
 *    credit to Apocalypse Laboratories, such as by showing
 *    "Based on <product> by Apocalypse Laboratories" or a
 *    similar notice;
 *  - You do not use the code for evil;
 *  - Rebranded compiled applications have significant
 *    differences in functionality;
 *  - and you provide your modified source code for download,
 *    under the terms of the GNU LGPL v3 or a comparable
 *    license.
 *
 * Compiled binaries cannot be redistributed or mirrored,
 * unless:
 *  - You have written permission from Apocalypse Laboratories;
 *  - Downloads are not available from Apocalypse Laboratories,
 *    not even behind a paywall or other blocking mechanism;
 *  - or you have received a multi-computer license, in which
 *    case you should take measures to prevent unauthorized
 *    downloads, such as preventing download access from the
 *    Internet.
 */
package net.apocalypselabs.symat;

import java.awt.Color;
import java.awt.Graphics2D;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JProgressBar;
import javax.swing.Painter;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.ColorUIResource;
import static net.apocalypselabs.symat.MainGUI.API_URL;
import static net.apocalypselabs.symat.MainGUI.APP_CODE;
import static net.apocalypselabs.symat.MainGUI.VERSION_NAME;
import static net.apocalypselabs.symat.MainGUI.loadFrame;

/**
 *
 * @author Skylar
 */
public class SplashScreen extends javax.swing.JFrame {

    /**
     * Creates new form SplashScreen
     */
    public SplashScreen() {
        initComponents();
        UIDefaults defaults = new UIDefaults();
        defaults.put("ProgressBar[Enabled].backgroundPainter", new ProgressPainter(false));
        defaults.put("ProgressBar[Enabled].foregroundPainter", new ProgressPainter(true));
        progBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
        progBar.putClientProperty("Nimbus.Overrides", defaults);

        setIconImage((new ImageIcon(
                getClass().getResource("icon.png"))).getImage());
        setLocationRelativeTo(null);
    }

    class ProgressPainter implements Painter<JProgressBar> {

        private final Color color;

        public ProgressPainter(boolean foreground) {
            if (foreground) {
                this.color = new Color(86, 161, 243);
            } else {
                this.color = new Color(59, 127, 243);
            }
        }

        @Override
        public void paint(Graphics2D gd, JProgressBar t, int width, int height) {
            gd.setColor(color);
            gd.fillRect(0, 0, width, height);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        progBar = new javax.swing.JProgressBar();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle(MainGUI.APP_NAME);
        setMaximumSize(new java.awt.Dimension(204, 260));
        setMinimumSize(new java.awt.Dimension(204, 260));
        setUndecorated(true);
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        progBar.setMaximumSize(new java.awt.Dimension(32767, 20));
        progBar.setMinimumSize(new java.awt.Dimension(10, 20));
        progBar.setPreferredSize(new java.awt.Dimension(146, 20));
        progBar.setString("");
        progBar.setStringPainted(true);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/net/apocalypselabs/symat/splash.gif"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(progBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jLabel5)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addGap(0, 0, 0)
                .addComponent(progBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        new Loader().start();
    }//GEN-LAST:event_formComponentShown

    /**
     * Bootstrapping everything.
     */
    private class Loader extends Thread {

        @Override
        public void run() {
            setProgress(10, "Starting up...");
            if (!MainGUI.skipPython) {
                // Python laggggsss when used for first time, this fixes the wait later.
                System.out.println("Warming up Python engine, to skip run with argument 'skippython'");
                setProgress(15, "Initializing code engine...");
                try {
                    CodeRunner python = new CodeRunner(true);
                } catch (Exception ex) {
                    // Ignore
                }
            }

            if (!MainGUI.skipEditor) {
                System.out.println("Preparing editor, to skip run with argument 'skipeditor'");
                setProgress(60, "Preparing editor...");
                // Get editor going too
                CodeEditor edit = new CodeEditor();
            }
            
            setProgress(75, "Checking for updates...");
            checkUpdates();

            setProgress(85, "Loading main interface...");
            new MainGUI().setVisible(true);
            setProgress(100, "Done!");
            dispose();
        }

        private void checkUpdates() {
            // Check for updates.
            try {
                Debug.println("Checking for updates...");
                URL url = new URL(API_URL + "testversion.php");
                InputStream is = url.openStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));

                String line = br.readLine();
                br.close();
                is.close();
                double version = Double.parseDouble(line.split("\\|")[0]);
                if (version > APP_CODE) {
                    if (PrefStorage.getSetting("update-ignore")
                            .equals(VERSION_NAME + "|" + line.split("\\|")[1])) {
                        System.out.println("An update was found, "
                                + "but has been ignored by the user.");
                    } else {
                        Debug.println("Update available.");
                        MainGUI.updateString = line.split("\\|")[1];
                        MainGUI.updateAvailable = true;
                    }
                } else {
                    Debug.println("No updates found.");
                }
            } catch (Exception e) {
                System.err.println("Fail:  Cannot check update server.  \n"
                        + "       Assuming local copy up-to-date.");
                Debug.stacktrace(e);
            }
        }

        /**
         * Set the progress bar.
         *
         * @param progress how full to make it (0 <= progress <= 100)
         * @param label The String to put on the label.
         */
        private void setProgress(int progress, String label) {
            final int prog = progress;
            final String lbl = label;
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    progBar.setIndeterminate(false);
                    progBar.setValue(prog);
                    progBar.setString(lbl);
                }
            });
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel5;
    private javax.swing.JProgressBar progBar;
    // End of variables declaration//GEN-END:variables
}
