package kindle.test.jni;

import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;

import com.amazon.kindle.kindlet.AbstractKindlet;
import com.amazon.kindle.kindlet.KindletContext;
import com.amazon.kindle.kindlet.ui.KOptionPane;
import com.lab126.util.fs.IUtil;


public class Main  extends AbstractKindlet implements ActionListener {
        private KindletContext ctx;
        private IJniLibrary my_jni_lib = null;
        private IUtil sys_lib = null;
        private JButton b1 = null;
        private JButton b2 = null;
        private JButton b3 = null;
        private JButton b4 = null;
        private JButton b5 = null;
        private JButton b6 = null;
        private JSpinner spinner = null;

        public void create(KindletContext context) {
        	super.create(context);
            this.ctx = context;
            JniLibrariesManager.getInstance().addLibInJar("kindle.test.jni.JniLibrary", 
			          									  "libjnilibrary.so",
			          									  this.ctx.getHomeDirectory().getAbsoluteFile().getPath()+"/");

            JniLibrariesManager.getInstance().addLibInSystem("com.lab126.util.fs.Util", 
					  									     "jnifsutil");
            try {
				my_jni_lib = (IJniLibrary) JniLibrariesManager.getInstance().createLibInstance("kindle.test.jni.JniLibrary");
			} catch (ClassNotFoundException c) {
				my_jni_lib = null;
			}
            
            try {
            	sys_lib = (IUtil) JniLibrariesManager.getInstance().createLibInstance("com.lab126.util.fs.Util");
			} catch (ClassNotFoundException c) {
				sys_lib = null;
			}
        }

        public void destroy() {
        	super.destroy();
        	//we have to explicit set all native classes to null so
        	//destroyLibInstances can do the work and clean up libraries 
        	my_jni_lib = null; sys_lib = null;
        	JniLibrariesManager.getInstance().destroyLibInstances();
        }
        
        public void actionPerformed(ActionEvent e) {
        	Random generator = new Random(System.nanoTime());
        	JButton b = (JButton) e.getSource();
        	String ret = null;
        	
        	if(b == b1) {
        		Integer n = new Integer(Math.abs(generator.nextInt())%200);
        		if(my_jni_lib.isGreaterThan100(n.toString()))
        			ret = n.toString()+" is greater than 100";
        		else
        			ret = n.toString()+" isn't greater than 100";
        	}
        	else if(b == b2) {
        		boolean c = generator.nextBoolean();
        		ret = my_jni_lib.converCase(c, "SAMPLE sample");
        	}
        	else if(b == b3) {
        		ret = my_jni_lib.add5Numbers(generator.nextInt(), generator.nextInt(), generator.nextInt(), generator.nextInt(), generator.nextInt());
        	}
        	else if(b == b5) {
        		int free1 = sys_lib.getFreeSpace("/");
        		int free2 = sys_lib.getFreeSpace("/mnt/us/");
        		ret = "Free space on / - "+ free1 + " MB\nFree space on /mnt/us/ - "+ free2+" MB";
        	}
        	else if(b == b6) {
        		int c1 = sys_lib.getCapacity("/");
        		int c2 = sys_lib.getCapacity("/mnt/us/");
        		ret = "Capacity on / - "+ c1 + " MB\nCapacity on /mnt/us/ - "+ c2+" MB";
        	}
        	else if(b == b4) {
        		for(int i = 0; i < (Integer)spinner.getValue(); i++) {
                	//we have to explicit set all native classes to null so
                	//destroyLibInstances can do the work and clean up libraries 
                	my_jni_lib = null;
                	JniLibrariesManager.getInstance().destroyLibInstances();
                	
                    try {
        				my_jni_lib = (IJniLibrary) JniLibrariesManager.getInstance().createLibInstance("kindle.test.jni.JniLibrary");
        			} catch (ClassNotFoundException c) {
        				my_jni_lib = null;
        			}

        			if (null == my_jni_lib) {
        				ret = "failed during " + i;
        				break;
        			}
        			else
        				ret = (i+1)+" times OK";
        		}
        	}

        	KOptionPane.showMessageDialog(this.ctx.getRootContainer(), ret);
        }

        public void start() {
    		Container pane = this.ctx.getRootContainer();
    		pane.removeAll();
    		pane.setLayout(new GridBagLayout());
    		GridBagConstraints gbc = new GridBagConstraints();
    		
        	if(my_jni_lib == null || sys_lib == null ) {
        		//UUUPS something is wrong with our lib lets display message and
        		//ask user to restart application or even whole kindle
        		pane.add(new JLabel("Couldn't initialize native library."), gbc);
        		gbc.gridy = 1;
        		pane.add(new JLabel("Please start application once again."), gbc);
        		gbc.gridy = 2;
        		pane.add(new JLabel("If this doesn't help please restart your Kindle."), gbc);
        	}
        	else {
	            try {
	            	b1 = new JButton("greater than 100");
	            	b2 = new JButton("string case");
	            	b3 = new JButton("sum");
	            	b4 = new JButton("init/destroy lib");
	            	b5 = new JButton("getFreeSpace");
	            	b6 = new JButton("getCapacity");

	            	SpinnerModel sm = new SpinnerNumberModel(10, 0, 40, 5);
	            	spinner = new JSpinner(sm);
	            	  
	            	JLabel picLabel = new JLabel((new ImageIcon(Main.class.getResource("/trollface.png"))));

	            	b1.addActionListener(this);
	            	b2.addActionListener(this);
	            	b3.addActionListener(this);
	            	b4.addActionListener(this);
	            	b5.addActionListener(this);
	            	b6.addActionListener(this);
	            	
	                gbc.gridx = 0;
	                gbc.fill = GridBagConstraints.HORIZONTAL;
	                gbc.fill |= GridBagConstraints.VERTICAL;
	                gbc.weightx  = 1;
	                gbc.weighty  = 0.1;
	                pane.add(b1, gbc);
	                
	                gbc.gridx = 1;
	                pane.add(b2, gbc);
	                
	                gbc.gridx = 2;
	                pane.add(b3, gbc);
	                
	                gbc.gridx = 3;
	                pane.add(b4, gbc);
	                
	                gbc.gridy = 1;
	                pane.add(spinner, gbc);
	                
	                gbc.gridx = 0;
	                pane.add(b5, gbc);
	                
	                gbc.gridx = 1;
	                pane.add(b6, gbc);
	                
	                gbc.gridx = 0;
	                gbc.gridy = 2;
	                gbc.gridwidth = 4;
	                gbc.weighty = 1;
	                pane.add(picLabel, gbc);
	            } catch (Throwable t) {}
        	}
        }
}