/********************************************************
* Speaker Verification Implemented Security             *
* CA4 Project                                           *
* Written by: Ronan Crowley (97084603)                  *
*        and  Paul Connolly (97307599)                  *
********************************************************/

import Audio.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;

public class Threshold extends JDialog {
    private JButton b[];
    public JTextField tf[];
    private String toSay[] = {      //Array containing everything to say in each threshold training case
        "THREE SO DOE SIX TWO FA NINE TEE NINE",
        "DOE FA EIGHT ME LA SO ONE SEVEN FIVE",
        "ONE FOUR THREE SIX FIVE RAY ME THREE TWO",
        "FOUR LA RAY THREE SEVEN NINE ONE FIVE SIX",
        "RAY ME TWO SEVEN DOE FA EIGHT RAY ONE"
    };
    private Container c;
    //Declare a sound handler.....
    private Audio.SoundBite s = null;
    private int numseconds = 10;        //Number of seconds to record for
    private GridLayout grid;
    ObjectInputStream input;
    ObjectOutputStream output;
    private String username;

    /** Constructor !
        @param User User that threshold is being set for.
        @param parent Calling Frame
    **/
    public Threshold(ObjectInputStream istream, ObjectOutputStream ostream, String User, Frame parent) {
        super(parent);
        username = User;
        input = istream;
        output = ostream;

        try {
            // Setup Audio system at 22050kHz       
            s = new Audio.SoundBite(false, false, Audio.SampleRate.R_22050, numseconds * Audio.SampleRate.R_22050 .toInt());
            jbInit();
        }
        catch(Exception e) {
          e.printStackTrace();
        }
        pack();
    }

    /** Component initialization **/ 
    private void jbInit() throws Exception
    {
      this.setTitle("Set Threshold for User: "+username);

      grid = new GridLayout( 6, 2 );

      c = getContentPane();
      c.setLayout( grid );

      //Create and add buttons and Textfields.....
      b = new JButton[5];
      tf = new JTextField[5];

      for (int i = 0; i < 5; i++ ) {
         tf[i] = new JTextField ((i+1)+")  "+toSay[i]);
         tf[i].setEditable(false);
         tf[i].setBackground(Color.white);
         c.add( tf[i]);
         b[i] = new JButton ("Record Sample");
         b[i].setToolTipText("Record as many times as you need !");
         c.add( b[i] );
      }

      //Add listeners
      b[0].addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e) {
            Record1_actionPerformed(e);
            }
      });
      b[1].addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e) {
            Record2_actionPerformed(e);
            }
      });
      b[2].addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e) {
            Record3_actionPerformed(e);
            }
      });
      b[3].addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e) {
            Record4_actionPerformed(e);
            }
      });
      b[4].addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e) {
            Record5_actionPerformed(e);
            }
      });

      JButton fin = new JButton("Finished");
      c.add(fin);
      fin.setMnemonic('f');
      fin.addActionListener(new ActionListener()  {
        public void actionPerformed(ActionEvent e){
            fin_actionPerformed(e);
            }
      });

      setSize( 500, 400 );
      setLocation(150, 150);
      show();
    }
    
    //Record ......
    public void Record1_actionPerformed(ActionEvent e) {recordSample("T0001.wav"); b[0].setText("Recorded");}
    public void Record2_actionPerformed(ActionEvent e) {recordSample("T0002.wav"); b[1].setText("Recorded");}
    public void Record3_actionPerformed(ActionEvent e) {recordSample("T0003.wav"); b[2].setText("Recorded");}
    public void Record4_actionPerformed(ActionEvent e) {recordSample("T0004.wav"); b[3].setText("Recorded");}
    public void Record5_actionPerformed(ActionEvent e) {recordSample("T0005.wav"); b[4].setText("Recorded");}
   
    /** Finished Button -> Ensures all files are recorded, then sends them to the Server **/
    public void fin_actionPerformed(ActionEvent e) {
        //Send files.......
        boolean allDone = true;
        for (int i=0; i<5; i++){
            if (b[i].getText().equals("Record Sample")){
                allDone = false;
            }
        }
        if (allDone){
            Sendfile[] transmit = new Sendfile[17];
            
            for (int i=0; i<5; i++){
                transmit[i] = new Sendfile();

                String title = new String("T000"+(i+1)+".wav");
                
                System.out.println("Sending: "+title);
                transmit[i].send("136.206.18.129", title);

                //Small pause
                int j=0;
                while (j<10000){j++;}
            }
        }

        // Recieve lines 3 & 4 from t.txt.
        double three =0.0;
        double four =0.0;
        try{
            String message=(String) input.readObject();

            int k=0;
            while (message.charAt(k) != ';'){
                k++;
            }
            three = Double.valueOf(message.substring(0, k).trim()).doubleValue();
            four = Double.valueOf(message.substring(k+1, message.length()).trim()).doubleValue();
        }
        catch (ClassNotFoundException cnfex){
            System.out.println("Unknown object type received");
        }
        catch ( IOException io)
        {
          io.printStackTrace();
        }
        catch ( NumberFormatException n) {
            System.out.println(n);
        }

        System.out.println("Line 3 = "+three);
        System.out.println("Line 4 = "+four);
        
        // Display option changing window
        (new setSecurity(this,output,username,three,four)).setVisible(true);

        s.dispose();
        dispose();
    }

    /** Method to record the sample specified
        @param name The WAV file to be created
    **/
    public void recordSample(String name) {
       try {
            System.out.println("\tStarted recording: "+name);

            {
                //From SoundBite class -> Start recording !
                s.recordStart();
                // s.recordWaitFor();
                // or
                s.recordWaitForGet();
            }
            //Savbe the WAV !
            s.save(name);
            System.out.println("\tRecording done: "+name+" saved !");

        } catch (Audio.SoundBiteException aud) {
            aud.printStackTrace();
            System.err.println("Audio Exception: " + aud.getMessage());
        }
   }
}