/***************************************************************************
 *   Copyright (C) 2009 by Paul Lutus                                      *
 *   lutusp@arachnoid.com                                                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TankCalcApplet.java
 *
 * Created on Feb 9, 2009, 5:09:12 PM
 */
package tankcalc;

import javax.swing.*;
import netscape.javascript.*;

/**
 *
 * @author lutusp
 */
public class TankCalcApplet extends javax.swing.JApplet {

    TankCalc mainPanel = null;
    Thread cookie_thread;
    String oldCookie = null;

    /** Initializes the applet TankCalcApplet */
    @Override
    public void init() {
        try {
            System.setProperty("awt.useSystemAAFontSettings", "on");
            System.setProperty("swing.aatext", "true");
        } catch (Exception e) {
        }
        mainPanel = null;
        try {
            // Set to use system-specific L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            // handle exception
        }
        // cookie update thread
        try {
            cookie_thread = new Thread() {

                @Override
                @SuppressWarnings("SleepWhileInLoop")
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(2000);
                        } catch (Exception e) {
                        }
                        writeCookie();
                    }
                }
            };
            cookie_thread.start();

            java.awt.EventQueue.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    initComponents();
                    mainPanel = new TankCalc(null, true, null);
                    setContentPane(mainPanel);
                    boolean verticalMode = false;
                    // read applet-tag specifier for vertical mode
                    String s = getParameter("verticalmode");
                    if (s != null) {
                        verticalMode = s.equals("true");
                    }
                    mainPanel.setVerticalMode(verticalMode);
                    SwingUtilities.invokeLater(
                            new Runnable() {

                                @Override
                                public void run() {
                                    String config = readCookie();
                                    mainPanel.setConfig(config);
                                }
                            });
                }
            });
        } catch (Exception ex) {
            System.out.println("applet init: " + ex);
        }
    }

    void writeCookie(String data) {
        if (data != null) {
            data = StringEscapeUnescape.stringToHex(data);
            try {
                if (data != null) {
                    java.util.Calendar c = java.util.Calendar.getInstance();
                    c.add(java.util.Calendar.MONTH, 1);
                    String expires = "; expires=" + c.getTime().toString();
                    JSObject browser = JSObject.getWindow(this);
                    if (browser != null) {
                        JSObject document = (JSObject) browser.getMember("document");
                        if (document != null) {
                            String cookie = data + expires;
                            document.setMember("cookie", cookie);
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("writeCookie failed: " + e);
            }
        }
    }

    public void writeCookie() {
        if (mainPanel != null) {
            // only write a cookie if the entries have changed
            String data = mainPanel.getConfig();
            if (data != null && oldCookie != null && !data.equals(oldCookie)) {
                //System.out.println("accepted data :" + data);
                writeCookie(data);
            }
            oldCookie = data;
        }
    }

    public String readCookie() {
        String result = null;
        try {
            JSObject browser = (JSObject) JSObject.getWindow(this);
            JSObject document = (JSObject) browser.getMember("document");
            //alert("readCookie myDocument = " + document);
            if (document != null) {
                String myCookie = (String) document.getMember("cookie");
                if (myCookie != null && myCookie.length() > 0) {
                    result = myCookie;
                    result = result.replaceFirst("(.*?);.*", "$1");
                }
            }
        } catch (Exception e) {
            System.out.println("readCookie exception: " + e);
        }
        if (result != null) {
            result = StringEscapeUnescape.hexToString(result);
        }
        return result;
    }

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

        setLayout(new java.awt.GridBagLayout());
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
