package tmcm.xTuringMachine;
import java.util.Vector;
import java.io.*;
import java.net.*;

class MachineLoader extends Thread {
   MachinePanel owner;
   int ID;
   URL url;
   String fileName, directory;
   String errorMessage;
   MachineLoader(URL url, MachinePanel owner, int ID) {
      this.url = url;
      this.owner = owner;
      this.ID = ID;
      start();
   }
   MachineLoader(String directory, String fileName, MachinePanel owner, int ID) {
      this.fileName = fileName;
      this.directory = directory;
      this.owner = owner;
      this.ID = ID;
      start();
   }
   public void run() {
      try { setPriority(getPriority() - 1); }
      catch (RuntimeException e) { }
      try { Thread.sleep(500 + (int)(500*Math.random())); }
      catch (InterruptedException e) { }
      boolean success = false;
      InputStream in = null;
      MachineData dataRead;
      try {
         if (url != null)
            in = url.openConnection().getInputStream();
         else
            in = new FileInputStream(new File(directory,fileName));
         dataRead = new MachineData();
         dataRead.read(in);
         owner.doneLoading(dataRead,ID);
      }
      catch (MachineInputException e) {
         errorMessage = "LOAD FAILED:  " + e.getMessage();
         owner.loadingError(ID);
      }
      catch (SecurityException e) {
         errorMessage = "LOAD FAILED, SECURITY ERROR:  " + e.getMessage();
         owner.loadingError(ID);
      }
      catch (Exception e) {
         errorMessage = "LOAD FAILED, ERROR:  " + e.toString();
         owner.loadingError(ID);
      }
      finally {
         if (in != null) {
            try { in.close(); }
            catch (IOException e) { }
         }
      }
   }
}

