/**
 * This is the main class.
 *
 */
package license4j.complete.application.example;

import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jgoodies.looks.windows.WindowsLookAndFeel;
import com.license4j.License;
import com.license4j.LicenseValidator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MainJFrame extends javax.swing.JFrame {

    // ProductLicense class
    private static ProductLicense productLicense;
    // License object
    private static License license;

    /**
     * Creates new form MainJFrame
     */
    public MainJFrame() {
        initComponents();

        this.setSize(800, 500);
        this.setLocationRelativeTo(null);

        // Read contents of html file and display on editor pane.
        InputStream in;
        BufferedReader br;
        try {
            in = this.getClass().getResourceAsStream("README.html");
            br = new BufferedReader(new InputStreamReader(in));
            String read;
            StringBuilder text = new StringBuilder();
            while ((read = br.readLine()) != null) {
                text.append(read);
            }

            jEditorPane1.setText(text.toString());
            jEditorPane1.setCaretPosition(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /*
     * Look and feel code
     */
    private static void setLookAndFeel() {
        if (System.getProperty("os.name").toLowerCase(Locale.US).startsWith("windows")) {
            try {
                UIManager.setLookAndFeel(new WindowsLookAndFeel());
            } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            try {
                UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
            } catch (UnsupportedLookAndFeelException ex) {
                Logger.getLogger(MainJFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        exitMenuItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        licenseMenuItem = new javax.swing.JMenuItem();
        licenseDetailMenuItem = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Main Product Window");

        jEditorPane1.setContentType("text/html"); // NOI18N
        jScrollPane1.setViewportView(jEditorPane1);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jMenu1.setText("File");

        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(exitMenuItem);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        jMenuItem2.setText("Cut");
        jMenu2.add(jMenuItem2);

        jMenuItem4.setText("Copy");
        jMenu2.add(jMenuItem4);

        jMenuItem5.setText("Paste");
        jMenu2.add(jMenuItem5);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Help");

        jMenuItem1.setText("Help Contents");
        jMenu3.add(jMenuItem1);

        licenseMenuItem.setText("License");
        licenseMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                licenseMenuItemActionPerformed(evt);
            }
        });
        jMenu3.add(licenseMenuItem);

        licenseDetailMenuItem.setText("License Details (for developers)");
        licenseDetailMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                licenseDetailMenuItemActionPerformed(evt);
            }
        });
        jMenu3.add(licenseDetailMenuItem);

        jMenuItem3.setText("About");
        jMenu3.add(jMenuItem3);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

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

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void licenseMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_licenseMenuItemActionPerformed
        /**
         * Display license dialog
         */
        new LicenseJDialog(this, true).setVisible(true);
    }//GEN-LAST:event_licenseMenuItemActionPerformed

    private void licenseDetailMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_licenseDetailMenuItemActionPerformed
        /**
         * Display license details dialog
         */
        new LicenseManagementJDialog(this, true).setVisible(true);
    }//GEN-LAST:event_licenseDetailMenuItemActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set look and feel */
        setLookAndFeel();

        // load settings and/or license from config file.
        productLicense = new ProductLicense();
        if (productLicense.loadLicense()) {
            license = productLicense.validateLicense(false);
        }

        if (license == null) {
            // license object is null, either there is no config file, or config
            // file does not include a license, so display licensing window.
            new LicenseJDialog(null, true).setVisible(true);
        } else {
            // license found
            switch (license.getValidationStatus()) {
                case LICENSE_VALID:
                    // license is valid, so continue running your software

                    if (license.isActivationRequired()) {
                        // if it requires activation, but not activated yet, display activation days remaining.
                        JOptionPane.showMessageDialog(null, "Activation required, days left: " + license.getLicenseActivationDaysRemaining(null), "Activation Requires", JOptionPane.ERROR_MESSAGE);
                    }

                    if (license.getLicenseText() != null && license.getLicenseText().getLicenseExpireDaysRemaining(null) > 0 && license.getLicenseText().getLicenseExpireDaysRemaining(null) < 30) {
                        // expiration date is set, and less than 30 days remaining, SO if you like display a message?
                        JOptionPane.showMessageDialog(null, "License will expire soon, days left: " + license.getLicenseText().getLicenseExpireDaysRemaining(null), "License Expiration", JOptionPane.ERROR_MESSAGE);
                    }

                    // Here check for license availability (blacklist). Method checks for license on server, 
                    // also it checks for activated licenses. If it returns -1 you can be sure that given
                    // license is deleted from server, so notify customer and close software because of illegal
                    // license usage.
                    // This check runs in a thread so it will not block software.
                    SwingWorker worker = new SwingWorker() {
                        int blacklistCheck;

                        @Override
                        protected void done() {
                            if (blacklistCheck == -1) {
                                System.err.println(blacklistCheck);
                                JOptionPane.showMessageDialog(null, "This is a blacklisted license. You are using an illegal license.\n\nSoftware will be closed.", "License Error", JOptionPane.ERROR_MESSAGE);
                                System.exit(-1);
                            }
                        }

                        @Override
                        protected License doInBackground() {
                            blacklistCheck = LicenseValidator.checkOnlineAvailability(productLicense.publicKey, license, 3000);

                            return null;
                        }
                    };
                    worker.execute();

                    break;
                default:
                    // ValidationStatus is not LICENSE_VALID, display a message dialog and display licensing window.

                    // YOU CAN CHECK FOR OTHER VALIDATION STATUS HERE LIKE EXPIRED, USAGE LIMIT REACHED ETC,
                    // THEN MAKE ANY OTHER THINGS.
                    JOptionPane.showMessageDialog(null, "License error: " + license.getValidationStatus(), "License Error", JOptionPane.ERROR_MESSAGE);

                    new LicenseJDialog(null, true).setVisible(true);
            }
        }


        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem licenseDetailMenuItem;
    private javax.swing.JMenuItem licenseMenuItem;
    // End of variables declaration//GEN-END:variables
}
