/*
 * ReceiveThread.java
 *
 * Created on October 19, 2003, 3:18 PM
 */

package PER.rover.control;

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;

/**
 *
 * @author  Eric Porter
 */
public class ReceiveThread extends Thread{
   public int minX, minY, maxX, maxY;
   public int x, y, pixels;
   
   private Reliagram rgram;
   private boolean keepGoing = true;
   private long staytonPicTime = 0, javaPicTime = 0;
   private long staytonTrackTime = 0, javaTrackTime = 0;
   private BufferedImage image;
   
   private static final int TRACK_SIZE = 16;
   
   /** Creates a new instance of ReceiveThread */
   public ReceiveThread(Reliagram reliagram) {
      rgram = reliagram;
      this.start();
   }
   //int imagesRead = 1;
   public void run() {
      while(keepGoing) {
         Datapack pack = rgram.receive();
         if(pack != null && pack.getLength() > 6) {
            long staytonTime = decodeStaytonTime(pack.getData());
            //System.out.println("got new packet, time is "+staytonTime+"\t"+System.currentTimeMillis());
            if(pack.getLength() == TRACK_SIZE) {
               byte data [] = pack.getData();
               minX = ByteUtil.unsign(data[6]);
               maxX = ByteUtil.unsign(data[7]);
               minY = ByteUtil.unsign(data[8]);
               maxY = ByteUtil.unsign(data[9]);
               x = ByteUtil.unsign(data[10]);
               y = ByteUtil.unsign(data[11]);
               pixels = ByteUtil.networkLongToInt(data, 12);
               //System.out.println(minX+" "+maxX+" "+minY+" "+maxY+" "+x+" "+y+" "+pixels);
               
               javaTrackTime = System.currentTimeMillis();
               staytonTrackTime = staytonTime;
            }else if(pack.getLength() > 1000){ //must be a picture
               if(staytonTime > staytonPicTime || System.currentTimeMillis() - javaPicTime > 5000) {
                  BufferedImage newImage;
                  try {
                     /*FileOutputStream fos = new FileOutputStream("stream/image"+(imagesRead++)+".jpg");
                     fos.write(pack.getData(), 6, pack.getLength()-6);
                     fos.close();*/
                     ByteArrayInputStream bais = new ByteArrayInputStream(pack.getData(), 6, pack.getLength()-6);
                     newImage = ImageIO.read(bais);
                     bais.close();
                  } catch(Exception e) {
                     newImage = null;
                     //System.out.println("Error reading in image! "+System.currentTimeMillis());
                  }
                  if(newImage != null) {
                     image = newImage;
			   /* write image out for webcast */
                /*     try {
                       ImageIO.write(image,"jpg",new java.io.File(rover.Rover.perPath+"rovercam.jpg"));
			     java.io.File oldFile = new java.io.File(rover.Rover.perPath+"rovercam.jpg");
			     java.io.File newFile = new java.io.File(rover.Rover.perPath+"streamcam.jpg");
		           if(oldFile.exists()){
  			       newFile.delete();
			       oldFile.renameTo(new java.io.File(rover.Rover.perPath+"streamcam.jpg"));    
                       }
                     }catch(java.io.IOException e){ System.out.println("Error writing to file "+rover.Rover.perPath+"rovercam.jpg"); }
				*/
                     javaPicTime = System.currentTimeMillis();
                     staytonPicTime = staytonTime;
                  }
               }/*else {
                  System.out.println("failed up to date check "+System.currentTimeMillis()+"st: "+staytonTime+" spt: "+staytonPicTime);
               }*/
            }
         }
      }
   }
   
   public void quit() {
      keepGoing = false;
   }
   
   /**
    * Gets the most recent image taken on the Stayton
    * @return the most recent picture the Stayton has send back.
    */
   public BufferedImage getRecentImage() {
      return image;
   }
   
   /**
    * Lets you know when the last image came.
    * @return the system time in ms when the last image came
    */
   public long getImageUpdateTime() {
      return javaPicTime;
   }
   
   /* Because communication takes place over UDP, packets could arrive out of order
    * I'm having the Stayton send its time to make sure that I don't replace current
    * information with out of date information.
    */
   private long decodeStaytonTime(byte [] arr) {
      long seconds = ByteUtil.networkLongToInt(arr, 0);
      long msecs = ByteUtil.networkShortToInt(arr, 4);
      return (seconds << 32) + msecs;
   }
   
}
