//import javax.xml.parsers.*;
//import org.xml.sax.*;
//import java.io.*;
//import org.w3c.dom.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import java.io.*;

public class SchemaParser
{
  FileReader fin;
  BufferedReader bin;
  StreamTokenizer input;
  Integer token = new Integer(0);
  String sval = new String();
  double nval = 0;
  boolean tag = false;
  boolean textNext = false;
  
  boolean parsingStim = false;
  boolean parsingUser = false;
  boolean parsingWafer = false;
  
  XMLobject parsedData;
   JLayeredPane layers = new JLayeredPane();
  
  //Code for XML Parsing Using DOM, removed for revisions
  //Document document;
  
  public SchemaParser()
  {
  }


  public SchemaParser(String fileName)
  {
    try
    {
     // fin = new FileReader(fileName);
     // bin = new BufferedReader(fin);
     // input = new StreamTokenizer(bin);
      input = new StreamTokenizer(getClass().getResourceAsStream(fileName));
      input.eolIsSignificant(false);
      input.slashStarComments(false);
      input.slashSlashComments(false);
      input.wordChars('<','<');
      input.wordChars('>','>');
      input.wordChars('/','/');
      input.wordChars('=','=');
      input.wordChars('?','?');
      input.wordChars('\'','\'');
      input.wordChars('-','-');
      input.wordChars('"','"');
      input.wordChars('!','!');
      
      parsedData = new XMLobject(fileName);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
  }

  
  
    public boolean checkParsable()
  {
    String construct = new String();
    
    try
    {
      token = new Integer(input.nextToken());
      nval = input.nval;
      sval = input.sval;

      while(input.ttype != input.TT_EOF)
      {
        if(input.ttype == input.TT_WORD)
        {
          if(sval.startsWith("<") || sval.startsWith("</"))
          {
            tag=true;
          }
          if(!(sval.startsWith("<") || sval.startsWith("</")) && !(sval.endsWith(">") || sval.endsWith("/>")))
          {
            tag=true;
          }
          if(sval.endsWith(">") || sval.endsWith("/>"))
          {
            tag=false;
            construct = construct + " " + sval;
          }
          if(tag == true)
            construct = construct + " " + sval;
        }
        else if(input.ttype == input.TT_NUMBER)
        {
          tag=true;
          construct = construct + " " + nval;
        }
        else if(input.ttype == input.TT_EOL || input.ttype == input.TT_EOF)
          ;
        
        token = new Integer(input.nextToken());
        nval = input.nval;
        sval = input.sval;
        if(tag == false)
        {
          //Handle special case where text appears on its own line but should be between tags
          if((input.ttype == input.TT_WORD)
              && (!(sval.startsWith("<") || sval.startsWith("</")) && !(sval.endsWith(">") || sval.endsWith("/>"))))
            textNext=true;
          else
            textNext=false;
          //Handle special case where numbers appear on their own line but should be between tags
          if(input.ttype == input.TT_NUMBER)
            textNext=true;
          
          if(!textNext)
          {
            //System.out.println(construct);
            SortTagInfo(construct);
            construct = "";
          }
        }
      }//while
    }
    catch(Exception e2)
    {
      
      JOptionPane.showMessageDialog(layers, "That file can not be opened.  To prvent this from happening, ensure that no fields are left blank",
          "Error", JOptionPane.ERROR_MESSAGE);
      return false;
    }
    return true;
  }
  
  
  
  
  public XMLobject Parse()
  {
    String construct = new String();
    
    try
    {
      token = new Integer(input.nextToken());
      nval = input.nval;
      sval = input.sval;

      while(input.ttype != input.TT_EOF)
      {
        if(input.ttype == input.TT_WORD)
        {
          if(sval.startsWith("<") || sval.startsWith("</"))
          {
            tag=true;
          }
          if(!(sval.startsWith("<") || sval.startsWith("</")) && !(sval.endsWith(">") || sval.endsWith("/>")))
          {
            tag=true;
          }
          if(sval.endsWith(">") || sval.endsWith("/>"))
          {
            tag=false;
            construct = construct + " " + sval;
          }
          if(tag == true)
            construct = construct + " " + sval;
        }
        else if(input.ttype == input.TT_NUMBER)
        {
          tag=true;
          construct = construct + " " + nval;
        }
        else if(input.ttype == input.TT_EOL || input.ttype == input.TT_EOF)
          ;
        
        token = new Integer(input.nextToken());
        nval = input.nval;
        sval = input.sval;
        if(tag == false)
        {
          //Handle special case where text appears on its own line but should be between tags
          if((input.ttype == input.TT_WORD)
              && (!(sval.startsWith("<") || sval.startsWith("</")) && !(sval.endsWith(">") || sval.endsWith("/>"))))
            textNext=true;
          else
            textNext=false;
          //Handle special case where numbers appear on their own line but should be between tags
          if(input.ttype == input.TT_NUMBER)
            textNext=true;
          
          if(!textNext)
          {
            //System.out.println(construct);
            SortTagInfo(construct);
            construct = "";
          }
        }
      }//while
    }
    catch(Exception e2)
    {
      
      
      e2.printStackTrace();
    }
    return parsedData;
  }

  private void SortTagInfo(String data)
  {
    String commentTag = new String("<!--");
    String initTag = new String("<?xml");
    String stimTag = new String("<stim");
    String stimCloseTag = new String("</stim>");
    String displayTag = new String("<display");
    String polesetTag = new String("<poleset");
    String poleTag = new String("<pole");
    String cueTag = new String("<que");
    String descripTag = new String("<descrip");
    String userTag = new String("<user");
    String userCloseTag = new String("</user>");
    String subjectTag = new String("<subject");
    String knownasTag = new String("<known as");
    String applicationTag = new String("<application");
    String waferTag = new String("<wafer");
    String waferCloseTag = new String("</wafer>");
    String statusTag = new String("<status");
    String results1Tag = new String("<results1");
    String results2Tag = new String("<results2");
    String results3Tag = new String("<results3");
    
    //System.out.println("*******************");
    //System.out.println("Parsing This:" + data);
    
    if(data.startsWith(commentTag,1))
      {}
    else if(data.startsWith(initTag,1))
      {}
    else if(data.startsWith(stimTag,1))
    {
      if(!parsingWafer)
      {
        parsingStim = true;
        //System.out.println(getValue(1,data));
        parsedData.setDatatype(1);
        parsedData.setStimName(getValue(1,data));
      }
      else
      {
        //System.out.println(getText(data));
        parsedData.setStimName(getText(data));
      }
    }
    else if(data.startsWith(stimCloseTag,1))
    {
      parsingStim = false;
    }
    else if(data.startsWith(displayTag,1))
    {
      //System.out.println(getValue(1,data));
      parsedData.setDisplayType(getValue(1,data));
      //System.out.println(getText(data));
      parsedData.setDisplayData(getText(data));
    }
    else if(data.startsWith(polesetTag,1))
    {
      //System.out.println(getValue(1,data));
      parsedData.setPoleNum(getValue(1,data));
      //System.out.println(getValue(2,data));
      parsedData.setPoleType(getValue(2,data));
    }
    else if(data.startsWith(poleTag,1))
    {
      //System.out.println(getValue(1,data));
      parsedData.setPoleIDs(getValue(1,data));
      //System.out.println(getValue(2,data));
      parsedData.setPoleValues(getValue(2,data));
    }
    else if(data.startsWith(cueTag,1))
    {
      //System.out.println(getText(data));
      parsedData.setPoleCues(getText(data));
    }
    else if(data.startsWith(descripTag,1))
    {
      //System.out.println(getText(data));
      parsedData.setPoleDescrip(getText(data));
    }
    else if(data.startsWith(userTag,1))
    {
      parsingUser = true;
      parsedData.setDatatype(2);
    }
    else if(data.startsWith(userCloseTag,1))
    {
      parsingUser = false;
    }
    else if(data.startsWith(subjectTag,1))
    {
      //System.out.println(getValue(1,data));
      parsedData.setSubjectName(getValue(1,data));
      //System.out.println(getValue(2,data));
      parsedData.setSubjectClass(getValue(2,data));
    }
    else if(data.startsWith(knownasTag,1))
    {
      //System.out.println(getText(data));
      parsedData.setKnownAs(getText(data));
    }
    else if(data.startsWith(applicationTag,1))
    {
      //System.out.println(getValue(1,data));
      parsedData.setAppID(getValue(1,data));
    }
    else if(data.startsWith(waferTag,1))
    {
      if(!parsingStim)
      {
        parsingWafer = true;
        parsedData.setDatatype(3);
        //System.out.println(getValue(1,data));
        parsedData.setWaferID(getValue(1,data));
        //System.out.println(getValue(2,data));
        parsedData.setWaferTime(getValue(2,data));
      }
      else
      {
        ;
      }
    }
    else if(data.startsWith(waferCloseTag,1))
    {
      parsingWafer = false;
    }
    else if(data.startsWith(statusTag,1))
    {
      //System.out.println(getText(data));
      parsedData.setWaferStatus(getText(data));
    }
    else if(data.startsWith(results1Tag,1))
    {
      //System.out.println(getText(data));
      parsedData.addWaferResults(getText(data));
    }
    else if(data.startsWith(results2Tag,1))
    {
      //System.out.println(getText(data));
      parsedData.addWaferResults(getText(data));
    }
    else if(data.startsWith(results3Tag,1))
    {
      //System.out.println(getText(data));
      parsedData.addWaferResults(getText(data));
    }
  }

  private String getValue(int location, String data)
  {
    String rippedSubstring = new String();
    char rippedSubChar = '-';
    
    int index = 0;
    
    for(int i = 0; i < location; i++)
    {
      if(i==0)
        index = data.indexOf('=');
      else
        index = data.indexOf('=',++index);
    }
    index=index+2;
    
    while(rippedSubChar != '"')
    {
      rippedSubChar = data.charAt(index);
      if(rippedSubChar != '"')
        rippedSubstring = rippedSubstring + rippedSubChar;
      index++;
    }
    
    return rippedSubstring;    
  }

  private String getText(String data)
  {
    String rippedSubstring = new String();
    char rippedSubChar = '-';
    int index = 0;
    
    index = data.indexOf('>');

    index++;
    if(data.charAt(index) == ' ')
      index++;
    
    while(rippedSubChar != '<')
    {
      rippedSubChar = data.charAt(index);
      if(rippedSubChar != '<')
        rippedSubstring = rippedSubstring + rippedSubChar;
      index++;
    }
    
    return rippedSubstring;    
  }

  //Code for XML Parsing Using DOM, removed for revisions
  /*public SchemaParser(String fileName)
  {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    
    try
    {
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(new File(fileName));
    }
    catch(SAXException sxe)
    {
      Exception x = sxe;
      if(sxe.getException() != null)
        x = sxe.getException();
      x.printStackTrace();
    }
    catch(ParserConfigurationException pce)
    {
      pce.printStackTrace();
    }
    catch(IOException ioe)
    {
      ioe.printStackTrace();
    }
  }

  public Document getDocument()
  {
    return document;
  }*/
}
