
package pws;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.net.URL;
import java.awt.print.*;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterJob;
import java.awt.print.Printable;
import java.awt.print.PrinterIOException;

/**
 *
 * @author  jessica
 */
public class Pws extends Applet{
    
    public static double [][] saveData = new double [800][1600];
    public static String fileTitle;
    public static int choseLine;
    static Panel content = new Panel(new BorderLayout());

    
    /** Creates a new instance of Pws */
    public Pws() {
        //Never do anything in an applet constructor!!!!!!!!!!!!!
    }//Pws()
    
    //Code to read file.
    public static void readFileData(URL url){
        //This will tell which line to read.
        byte [] rec = new byte [1024];
        int line = 0;
        //Offset is the time each new line begins.
        double offset = 0.0;
        int sample = 0;
        try {
            InputStream fis = url.openStream();
            int bytesRead;
            int totalBytesRead = 0;
            do {
                bytesRead = fis.read(rec, totalBytesRead, 1024 - totalBytesRead);
                totalBytesRead += bytesRead;
            } while (bytesRead != -1 && totalBytesRead < 1024);
            if (bytesRead == -1) {
                System.out.println("Error reading engineering header record.");
                return;
            }//if (fis.read(rec) != rec.length)
            fileTitle = new String();
            
            for (int i=248; i<1024 && rec[i]!=0; i++) {
                fileTitle = fileTitle + ((char)rec[i]);
            }//for (int i=248; i<1024 && rec[i]!=0; i++)
            
            bytesRead = 0;
            while (bytesRead != -1) { 
            /*This reads entire file, 1-800 lines.
             *It saves 1 line of data per row. One entire row is the y coordinates,
             *the length of the row is the amount of the x coordinates.*/
                totalBytesRead = 0;
                do {
                    bytesRead = fis.read(rec, totalBytesRead, 1024 - totalBytesRead);
                    totalBytesRead += bytesRead;
                } while (bytesRead != -1 && totalBytesRead < 1024);
                if (bytesRead == -1) continue;
                line = ( ((int) rec[22] & 0xFF) << 8) | ((int)rec[23] & 0xFF);
                int counter = 0;
                for (int i = 220; i<220+800; counter++, i++) {
                    sample = ((int) rec[i] & 0xF0) >>>4;
                    saveData[line-1][counter] = sample;
                    counter++;
                    sample = (int)rec[i] & 0x0F;
                    saveData[line-1][counter] = sample;
                }//for (int i = 220; i<220+800; counter++, i++)
            }//((fis.read(rec)) != -1)
            fis.close();
        }/*try*/
        catch (IOException e) {
            e.printStackTrace();
        }//catch
    }//public static void readFileData(File infile)
    
    public static void setLine(int set) {
        double [] xData = new double [1600];
        double [] yData = new double [1600];
        double offset;
        choseLine = set-1;
        for(int col=0; col<saveData[choseLine].length; col++) {
            yData[col] = saveData[choseLine][col]-7.5;
        }//for(int col=0; col<saveData[choseLine].length; col++)
        offset = (set - 1)*0.06;
        //offset = (set - 1)*0.06*1000;
        
        for(int i=0; i<1600; i++) {
            xData[i] = ((1600.0/28800.0*1000.0)*i)/1599;
        }//for(int i=0; i<1600; i++)
        
        //This is code to update Title with each line movement of scrollbar.
        if (set < 2) System.out.println("This is fileTitle: " + fileTitle);
        
        StringBuffer setString = new StringBuffer(Integer.toString(set));
        StringBuffer updatedTitle = new StringBuffer(fileTitle);
        //Following line returns position of space after 1st '.'
        int nextSpace = fileTitle.indexOf(" ", fileTitle.indexOf('.'));
        String updated = "";
        if (set > 0 && set < 10){
            //Insert .00 at position 0.
            setString = setString.insert(0, ".00");
        }//if
        if (set > 9 && set < 100) {
            // Insert .0 at position 0.
            setString = setString.insert(0, ".0");
        }//if
        if (set > 99 && set < 1000) {
            //Insert . at position 0.
            setString = setString.insert(0, ".");
        }//if
        updatedTitle = updatedTitle.insert(nextSpace, setString);
        int len_updatedTitle = updatedTitle.length();
        int index = updatedTitle.indexOf(".");
        nextSpace = updatedTitle.indexOf(" ", index);
        int indexOfStartDate = nextSpace+1;
        
        String startDate = updatedTitle.substring(nextSpace+1);
        final pwDate DATE = new pwDate(startDate);
        pwDate currentDate = DATE.add(offset);
        String currentDateString = currentDate.getTimeAsString(pwDate.context.DATE);
        System.out.println("CurrentDateString: " + currentDateString);
        String currentTimeInMilli = currentDate.getTimeAsString(pwDate.context.MILLISECONDS);
        System.out.println("Current time in milliseconds: "+currentTimeInMilli);
        String currentDateAndTime = currentDateString+"T"+currentTimeInMilli+"Z";
        System.out.println(currentDateAndTime);
        updatedTitle.replace(nextSpace+1, len_updatedTitle, currentDateAndTime);
        updated = new String(updatedTitle);
        graphTool.setTitle(updated);
        graphTool.addData(xData, yData);
    }// public static void setLine
    
    public static Panel initPlot(URL url) throws Exception{
        Scrollbar bar;
        final Label label;
        graph = new pwCanvas();
        pwRow row = new pwRow(graph, 0.1, 0.9);
        pwColumn col = new pwColumn(graph, 0.1, 0.9);
        pwAxis yAxis = new pwAxis(new Datum(-7.5), new Datum(7.5), row, col, pwAxis.VERTICAL);
        xAxis = new pwAxis(new Datum(0.0), new Datum(55.6), row, col, pwAxis.HORIZONTAL);
        graphTool = new pwStackedSymbolPlot((XMultiYDataSet)null, xAxis, yAxis, row, col);
        graphTool.setPsym(Psym.LINES);
        graph.addCanvasComponent(graphTool);
        graph.addCanvasComponent(xAxis);
        graph.addCanvasComponent(yAxis);
        readFileData(url);
        setLine(1);
        content.add(graph,BorderLayout.CENTER);
        content.setBackground(Color.white);
        Panel scrollbar = new Panel(new BorderLayout());
        bar = new Scrollbar(Scrollbar.HORIZONTAL,1,1,1,801);
        //This get the int value of what the slider represents.
        scrollbar.add(bar,BorderLayout.SOUTH);
        label = new Label("Line: 1", Label.CENTER);
        
        bar.addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent e) {
                int b = e.getValue();
                String val = "Line: "+b;
                label.setText(val);
                setLine(b);
                graph.repaint();
            }//addAdjustmentListener
        });
        scrollbar.add(label,BorderLayout.CENTER);
        content.add(scrollbar,BorderLayout.SOUTH);
        return content;
    }//public static Panel initPlot(URL url) throws Exception
   
    public void paint(Graphics g){
        Frame f = new Frame();
        Panel p = new Panel();
        p = content;
        f.add(p);
        setVisible(true);
    }//public void paint(Graphics g)
    
    public void init() {
        try {
            String s = getParameter("DataFile");
            URL url = new URL(getCodeBase(), s);
            System.out.println(url);
            Panel p = initPlot(url);
            setLayout(new BorderLayout());
            add(p,"Center");
        }//try
        catch (Exception e) {
            e.printStackTrace();
        }//catch
    } //public void init()
    
    public static void main(String[] args) {
        if (args.length<1) {
            System.out.println("Usage: java pwswfrmlist /path/to/input/file)");
            return;
        }//if
        String string = (args[0]);
        Panel p;
        URL url;
        Frame f = new Frame("New Frame");
        
        try {
            url = new URL(string);
            System.out.println("Opening URL "+url);
            p = initPlot(url);
            f.add(p);
        }//try
        
        catch (Exception e) {
            try {
                String absFile = (new File(string).getCanonicalPath());
                String urlstr= "file://" + absFile;
                System.out.println("Opening URL "+urlstr);
                url= new URL(urlstr);
                p = initPlot(url);
                f.add(p);
            }//try
            catch (Exception a) {
                a.printStackTrace();
                Label lab = new Label(a.getMessage());
                f.add(lab);
            }//catch
        }//catch
        
        f.setSize(800,400);
        f.setLocation(100,100);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }//addWindowListener
        });
        
        f.setVisible(true);
    }//main
}//public class Pws

