package lejos.pc.tools;
import lejos.pc.comm.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.io.*;

/**
 * Downloads  data from the DataLogger running on a MXT <br>
 * Uses Bluetooth
 * The data can be copied and pasted into a spread sheet for analysis & graphing <br>
 * status field shows messages 
 * @author Roger Glassey revised  07.11.2007
 *
 * 
 */
public class DataViewer extends JFrame implements ActionListener
{


   private JButton startButton = new JButton("Start download");
   private JToggleButton usbButton = new JToggleButton("USE Bluetooth");
   private TextField statusField = new TextField(20);
   private TextField lengthField = new TextField(5);
   private TextField nameField = new TextField(12);
   private int _recordCount = 0;
   private int _rowLength = 4;
   private String _nxt = "NXT"; 
   private boolean _useUSB = true;
   private DataInputStream dataIn = null;
   private InputStream is = null;
   private OutputStream os = null;
   private Connector con;
   private boolean _connected = false;


   /**
    * screen area to hold the downloaded data
    */
   private TextArea theLog;


   /**
    * Constructor builds GUI
    */
   public DataViewer() 
   {		
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setTitle("View Data from NXT Datalogger");
      setSize(500,600);
      JPanel p1 = new JPanel();  //holds  button and text field
      p1.add(new JLabel("Row Length:"));
      p1.add(lengthField);
      lengthField.setText("2");
      p1.add(new JLabel("name or address"));
      p1.add(nameField);
      startButton.addActionListener(this);
      JPanel p2 = new JPanel();//  holds label and text field
      p2.add(usbButton);
      usbButton.addActionListener(this);
      p2.add(startButton);
      p2.add(new JLabel("  Status:"));
      p2.add(statusField);

      JPanel panel = new JPanel();  // North area of the frame
      panel.setLayout(new GridLayout(2,1));
      panel.add(p1);
      panel.add(p2);;
      add(panel,BorderLayout.NORTH);
      theLog = new TextArea(40,40); // Center area of the frame
      getContentPane().add(theLog,BorderLayout.CENTER);
      statusField.setText("using  USB");

   }
   /**
    * Required by action listener; only action is generated by the get Length button
    */	
   public void actionPerformed(ActionEvent e)
   {
      if(e.getSource()== startButton)
      {
         _rowLength = Integer.parseInt(lengthField.getText());
         _nxt = nameField.getText();	
         _recordCount = 0;
         startDownload();
      }
      if(e.getSource()==usbButton)
      {
         _useUSB = !_useUSB;
         if(_useUSB){
            setMessage("using USB");
         }
         else setMessage("using Bluetooth");          
      }
   }
   /**
    * Initialize the display Frame <br>
    */		
   public static void main(String[] args)
   {
      DataViewer frame = new DataViewer();
      frame.setVisible(true);

   }
   private void connect()
   {
      _nxt = nameField.getText(); 
      setMessage("Connecting");
      con = new Connector();
      if (! con.connectTo(_nxt,_useUSB)) System.exit(1);


      dataIn = con.getDataIn();
      is = con.getInputStream();
      if(dataIn != null)System.out.println(" dataIn OK");
      os = con.getOutputStream();
      _connected = true;
//    the NXT is waiting for an incoming byte before it starts transmitting 
   }
   private void startDownload()
   {  
      if(!_connected)connect(); 
      int b = 15;
      try //handshake - ready to read data
      {     
         os.write(b);
         os.flush();
      } catch(IOException e) {System.out.println(e+" write "); }
      setMessage("write "+b);
      setMessage("reading");
      float x = 0;
      try
      {   
         int length = dataIn.readInt();
         setMessage("length "+length);
         for (int i = 0; i < length; i++)
         {
            if(0 == _recordCount%_rowLength)theLog.append("\n"); 
            x = dataIn.readFloat();
            theLog.append(x+ "\t ");
            _recordCount++;
         } 
//         dataIn.close();
      } catch(IOException e) {System.out.println(e); }
   }


   /**
    *messages generated show in the status Field
    */
   public void  setMessage(String s){ statusField.setText(s);}
}	
