import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.border.*;
import java.util.*;
import java.io.*;
import java.net.URLConnection;
import java.net.URL;
import java.net.MalformedURLException;

public class Control
{
  
  JLayeredPane layers = new JLayeredPane();
  private Vector stims;
  private String surveyFile;
  private Vector questions = new Vector(); //our vector of xml questions
  private SurveyObject survey;
  private int current; //if current is -1 then vector empty
	private Vector data; //vector of question data to be printed
	private JApplet theApplet;
	private AppletContext context;
	
	private class Info
	{

		private String question;
		private String ID1;
		private String ID1num;
		private String ID2;
		private String ID2num;
		private String ID3;
		private String ID3num;
		
		public Info()
		{
			
			question = "";
			ID1 = "";
			ID1num = "d";
			ID2 = "";
			ID2num = "d";
			ID3 = "";
			ID3num = "d";

		
		}
		
		public Info(String q, String id1, String id1n, String id2, String id2n,
								String id3, String id3n)
		{

			question = q;
			ID1 = id1;
			ID1num = id1n;
			ID2 = id2;
			ID2num = id2n;
			ID3 = id3;
			ID3num = id3n;


		}
		
		public String getQuestion()
		{
			return question;
		}
		
		public String getID1()
		{	
			return ID1;
		}
		
		public String getID1num()
		{	
			return ID1num;
		}
		
		public String getID2()
		{	
			return ID2;
		}
		
		public String getID2num()
		{	
			return ID2num;
		}
		
		public String getID3()
		{	
			return ID3;
		}
		
		public String getID3num()
		{	
			return ID3num;
		}
		
	}
	
  public Control()
  {
		stims = new Vector();
		current = -1; //set survey to beginning
		
		data = new Vector();
  }
  
    public Control(JApplet applet)
  {
		stims = new Vector();
		current = -1; //set survey to beginning
		
		data = new Vector();
		context = applet.getAppletContext();
		
  }
   
  public Control(String file, File dir, JApplet applet)
  {
  		surveyFile = file;
		theApplet = applet;

			 

			if(file.endsWith(".wsl"))
			{
				survey = new SurveyObject(surveyFile);
      				survey.readInSurvey();

  	    			//get that parsed list of elements and store
    	  			stims = new Vector(survey.getStimList());

				Integer size = new Integer(stims.size());


					//open each elements xml file, parse and store

			for(int i = 0; i < stims.size(); i++)
      			{

				try{


				//String opening = dir.getCanonicalPath() + "/" + (String)stims.elementAt(i);
				String opening = (String)stims.elementAt(i);
				
        			SchemaParser input = new SchemaParser(opening);
        			XMLobject stim = new XMLobject(opening);
        			stim = input.Parse();
        			questions.addElement(stim);
				}
				catch(Exception e)
				{
					e.printStackTrace();

				}
			}
					
			}
			else
      {
        		JOptionPane.showMessageDialog(null, "Please open a \"Wafers Survey File\" or .wsl",
         		"Error", JOptionPane.ERROR_MESSAGE);
			}

			current = 0;
			data = new Vector();
  }


 	public void gotoFirst()
	{
	 	data.removeAllElements();
		current = 0;
	}
	
	public void gotoNext(SRPole stimPole)
	{
		String s = new Integer(current+1).toString();
	
		XMLobject txml = (XMLobject)questions.elementAt(current);
		Info temp = new Info(s, txml.getPoleIDs(0), stimPole.getCanvas().getPercent(1),txml.getPoleIDs(1),
		stimPole.getCanvas().getPercent(2),txml.getPoleIDs(2), stimPole.getCanvas().getPercent(3));
		
		data.add(temp);
		
		current++;
	}
  
	public void goBack()
	{
		
		if(current > 0 && !questions.isEmpty())
		{
			data.remove(current);
			current--;
		}
		else
		{
			current = 0;
		}
	}
	
	public XMLobject getObject()
	{
		return (XMLobject)questions.elementAt(current);
	}
	
	public boolean finished()
	{
		if(current < questions.size())
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	
	public void processUser(String userName)
	{
		boolean found = false;
		String str;
    		
		URL url=null;
		try{
			url = new URL ("http", "ctl.unbc.ca",
        				"/survey/Users.txt" );
    			
		}
		catch (MalformedURLException  e ) {
		
		JOptionPane.showMessageDialog(layers, "Bad Url",
      			"Error", JOptionPane.ERROR_MESSAGE);
		}
 		
				
		try{
		InputStream in = url.openStream();
      		BufferedReader dis =
        	new BufferedReader(new InputStreamReader(in));
		while((str = dis.readLine()) != null)
		{
			
			
			if(str.equals(userName))
			{
					
				found = true;
				checkTaken(userName);
				break;
			}
		}
			in.close();
		}
		catch(IOException e){
			JOptionPane.showMessageDialog(layers, "Bad News",
      			"Error", JOptionPane.ERROR_MESSAGE);
		
		}
		
		catch(Exception g){}
		
		
		if(found == false)
		{				
			JOptionPane.showMessageDialog(layers, "User name not found.  Please inform instructor.",
      			"Error", JOptionPane.ERROR_MESSAGE);
			try
				{

				    context.showDocument(new URL("http", "ctl.unbc.ca", "/survey/Wafers/rejected.html"));

				}
				catch (MalformedURLException ey)
				{
    					//ey.printStackTrace();
						JOptionPane.showMessageDialog(layers, "Bad News",
      					"Error", JOptionPane.ERROR_MESSAGE);
				}
			
		}
		
	
	}
	
	public void checkTaken(String userName)
	{
		
		String str;
		URL url=null;
		try{
    			url = new URL ("http", "ctl.unbc.ca",
        					"/survey/Taken.txt" );
    		}
		catch (MalformedURLException  e ) {}
 		
				
		try{
		InputStream in;
		in = url.openStream();
      		BufferedReader dis =
        	new BufferedReader(new InputStreamReader(in));
		
		while((str = dis.readLine()) != null)
		{
			if(str.equals(userName))
			{
				JOptionPane.showMessageDialog(layers, "Survey can only be taken once.",
      			"Error", JOptionPane.ERROR_MESSAGE);
				
				try
				{

				    context.showDocument(new URL("http", "ctl.unbc.ca", "/survey/Wafers/rejected.html"));

				}
				catch (MalformedURLException ex)
				{
    					//ex.printStackTrace();
						JOptionPane.showMessageDialog(layers, "Bad News",
      					"Error", JOptionPane.ERROR_MESSAGE);
				}
				
			
			}
		}	
			in.close();
		}
		catch(IOException f){}
		
	
	}
	
	public void writeUser(String name) throws Exception
	{
	
		String theName = name;
		
		SendName("\n" + theName);
		
	}
	
	public void writeData() throws Exception
	{
		
		String s = surveyFile.replaceAll("wsl", "dat");
		
		try {
        	
		String appdata = new String();
		
		appdata = "NEW USER \n";
		SendData(appdata);
				
				for(int i = 0; i < data.size(); i++)
				{
					Info temp = (Info)data.elementAt(i);
					/*out.write(temp.getQuestion() + "\n");
					out.write(temp.getID1() + ": " + temp.getID1num() + "\n");
					out.write(temp.getID2() + ": " + temp.getID2num() + "\n");
					out.write(temp.getID3() + ": " + temp.getID3num() + "\n\n");
					*/
					
					appdata = temp.getQuestion() + "\n";
					SendData(appdata);
					
					appdata = temp.getID1() + ": " + temp.getID1num() + "\n";
					SendData(appdata);
					
					appdata = temp.getID2() + ": " + temp.getID2num() + "\n";
					SendData(appdata);
					
					appdata = temp.getID3() + ": " + temp.getID3num() + "\n\n";
					SendData(appdata);
					
        			}
				
				//out.flush();
				//out.close();
    		} 
		catch (IOException e) {
    	e.printStackTrace();
		}
	}
	
	public void SendData(String data) throws Exception
	{
		URL url = new URL("http","ctl.unbc.ca",
        	"/cgi-bin/writeout.pl");
        	URLConnection con = url.openConnection();
		
        	con.setDoOutput(true);
        	con.setDoInput(true);
        	con.setUseCaches(false);
        	con.setRequestProperty("Content-type", "text/plain");
        	con.setRequestProperty("Content-length", data.length()+"");
		
		 PrintStream out =
                new PrintStream(con.getOutputStream());
                out.print(data);
                out.flush();
                out.close();

                DataInputStream in =
                new DataInputStream(con.getInputStream());
                String s;
                while ((s = in.readLine()) != null) {
                }
                in.close();
        }
	
	public void SendName(String data) throws Exception
	{
		URL url = new URL("http","ctl.unbc.ca",
        	"/cgi-bin/writename.pl");
        	URLConnection con = url.openConnection();
		
        	con.setDoOutput(true);
        	con.setDoInput(true);
        	con.setUseCaches(false);
        	con.setRequestProperty("Content-type", "text/plain");
        	con.setRequestProperty("Content-length", data.length()+"");
		
		 PrintStream out =
                new PrintStream(con.getOutputStream());
                out.print(data);
                out.flush();
                out.close();

                DataInputStream in =
                new DataInputStream(con.getInputStream());
                String s;
                while ((s = in.readLine()) != null) {
                }
                in.close();
        }
	
	
	
	
}

