import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

/**
 * Created by Dorien Herremans on 09/02/15.
 */
public class TranceExperiment extends JFrame implements ActionListener {


//    /private TranceExperiment ex;
    //define variables
    private Integer experimentState;
    private Integer numberOfInstances;
    private JLabel expText;
    private JLabel instructionsText;
    private JLabel scaleLabelText;
    private JLabel participantText;
    private boolean testMode;
    private JLabel userNumber;
    private JButton startButton;
    private Integer stimDuration;
    private ButtonGroup resultButtonGroup;
    private JPanel buttonsPanel;
    private ArrayList<Integer> results;
    private ArrayList<Integer> played;
    private ArrayList<String> simuli;
    private Properties settings = new Properties();
    private String participantNumber;
    private JTextField userText;
    private JLabel enjoyment;
    private ArrayList<String[]> inputList;
    String[] header;
    private Integer instanceNumber;
    private JLabel scaleLabel;
    private boolean testPhase;
    private JLabel titleText;
    private Integer testNumber;
    private PrintWriter out;


    /**
     * set properties of the window
     */
    public TranceExperiment() throws IOException {



        //set global variables

        testMode = false; //initialise just in case
        readConfig();
        experimentState = -7;
        //numberOfInstances = Integer.valueOf(settings.getProperty("numberOfInstances").toString());

        if (testMode) {
            stimDuration = 1000; //28000; //in ms
        }
        else{
            stimDuration = 28000; //28000;
        }
        results = new ArrayList<Integer>();
        results.clear();
        played = new ArrayList<Integer>();
        played.clear();

        setTitle("Simple example");
        //setSize(600, 400);
        //getContentPane().setPreferredSize( Toolkit.getDefaultToolkit().getScreenSize());
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setLocationRelativeTo(null);
        setTitle(settings.getProperty("title").toString());
        setLayout(new BorderLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }


    /**
     * play sound
     *
     * @throws Exception
     */
    public void mediaPlayer()
            throws Exception {
//        // open the sound file as a Java input stream


        //System.out.print("hier" + testPhase + testNumber);
        String soundFile;
//        String soundFile = "./data/1.wav";
        if (testPhase) {
            //System.out.println("instance: " + instanceNumber);
            if (testNumber == 0){
                soundFile = "./data/practice_trials/ABCD-ACDE/EmCAmD-EmAmDBm/EmCAmD-EmAmDBm.wav";
                //soundFile = "./data/4.wav";
                testNumber++;
                //System.out.print("./data/practice_trials/ABCD-ACDE/EmCAmD-EmAmDBm/EmCAmD-EmAmDBm.wav");
            }
            else {
                soundFile = "./data/practice_trials/AABB-ABCC/DDGG-DGAA/DDGG-DGAA.wav";
            }
        }
        else {
            //System.out.print("instanceNum: " + instanceNumber);
            soundFile = "./data/" + inputList.get(instanceNumber-1)[0];
        }


        InputStream audioInputStream = new FileInputStream(soundFile);
//
//        // create an audiostream from the inputstream
        AudioStream audioStream = new AudioStream(audioInputStream);
        // play the audio clip with the audioplayer class
        AudioPlayer.player.start(audioStream);
//        System.out.print(AudioPlayer.player.getState());
//        AudioInputStream audioIn = null;
//        URL url = this.getClass().getResource("data/1.wav");
//        System.out.print(url.getFile());


        //mp3 converter

//        int BUFFER_SIZE = 176400; // 44100 x 16 x 2 / 8
//
//        byte[]  buffer = new byte[BUFFER_SIZE];
//
//        AudioInputStream in = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, AudioSystem.getAudioInputStream(new File ("./data/1.mp3")));
//        AudioFormat audioFormat = in.getFormat();
//
//        SourceDataLine line = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioFormat));
//        line.open(audioFormat);
//        line.start();
//
//        while (true) {
//            int n = in.read(buffer, 0, buffer.length);
//            if (n < 0) {
//                break;
//            }
//            line.write(buffer, 0, n);
//        }
//        line.drain();
//        line.close();



//            standard audio player
//        Clip clip = AudioSystem.getClip();
//        URL url = this.getClass().getResource("data/1.mp3");
//        AudioInputStream aiStream = AudioSystem.getAudioInputStream(url);
//        clip.open(aiStream);
//        clip.start();

        //add the played soundfile to the list
        if (!testPhase && results.size()>0) {
            played.add(instanceNumber);
//            for (int i = 0; i < results.size()-1; i++) {
                int i = results.size()-1;
                //todo, put right length
                out.println(participantNumber + ", " + results.get(i) + ", " + inputList.get(i)[0] + ", " + inputList.get(i)[1] + ", " + inputList.get(i)[2] + ", " + inputList.get(i)[3] + ", " + inputList.get(i)[4] + ", " + inputList.get(i)[5] + ", " + inputList.get(i)[6]+ ", " + inputList.get(i)[7]);
//            }
            out.flush();
        }
    }



    /**
     * Do this on click of the button
     *
     * @param e
     */
    public void actionPerformed(ActionEvent e) {
//        System.out.print("state: " + experimentState);
//        System.out.print("inputlist: " + inputList.size());
//        System.out.print("Results: " + results.size());

        if ((experimentState == -6)){

            //to remove this page
            //change the state of the experiment
            startButton.setText("Continue");
            scaleLabel.setVisible(false);
            experimentState++;

        }


        //if startstate
        if (experimentState == -7) {


            //read in the participant number
            if (!userText.getText().isEmpty())   {
                participantNumber = userText.getText();



                //write the output file
                //prepare headers and open file

                FileWriter resultsFile = null;
                try {
                    resultsFile = new FileWriter("results" + participantNumber + ".csv", true);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                BufferedWriter bufferedResultsFile = new BufferedWriter(resultsFile);
                out = new PrintWriter(bufferedResultsFile);

                //write headers
                out.print("Participant, result");
                for (String a : header) {
                    out.print(", " + a);
                }
                out.print("\n");





                userNumber.setText(participantNumber);

            //remove the user number text thingie
            userText.setEnabled(false);
            userText.setVisible(false);



            //say: get ready
            expText.setText("");
                instructionsText.setVisible(true);
            participantText.setText("");
            participantText.setVisible(false);
            //scaleLabel.setVisible(true);

            //change the state of the experiment
            experimentState++; }

        }
//        else if ((experimentState == -6)){
//
//            //say: get ready
//            expText.setText(settings.getProperty("initial").toString());
//            startButton.setText("Continue");
//            scaleLabel.setVisible(false);
//
//            //change the state of the experiment
//            experimentState++;
//
//        }

        else if ((experimentState == -2)||(experimentState == -3)||(experimentState == -5)||(experimentState == -4)) {

            instructionsText.setVisible(false);
            //System.out.print("a");
            //even experiment state (first screen of a stimuli)
            if (experimentState % 2 != 0) {
                //first screen
                //System.out.print("b");


                if ((resultButtonGroup.getSelection() == null) && buttonsPanel.isVisible() == true) {
                    //don't do anything
                    //when radiobuttons not pressed count back timer and say select or do nothing


                } else {

                    if (experimentState ==-5) {
                        titleText.setVisible(false);
                        expText.setText(settings.getProperty("ready1st").toString());
                    } else {
                        expText.setText(settings.getProperty("ready").toString());

                    }
                    //if it's the first screen: ask if ready
                    buttonsPanel.setVisible(false);
                    scaleLabelText.setVisible(false);
                    enjoyment.setVisible(false);
                    //buttonsPanel.setEnabled(false);

                    if (resultButtonGroup.getSelection() != null) {
                        //GET THE VALUES AND STORE THEM
                        //System.out.print(getSelectedButtonText(resultButtonGroup));
                        //results.add(Integer.valueOf(getSelectedButtonText(resultButtonGroup)));
                        //results.add(Integer.valueOf(resultButtonGroup.getSelection()));
                        //change the state of the experiment
                        experimentState++;
                        //instanceNumber++;
                    }



                    //deselectButtons(resultButtonGroup);


                }

                if (experimentState == -5) {
                    experimentState++;
                }


            } else {
                //else: play sound

                Thread t2 = new Thread(new Runnable() {
                    public void run() {
                        // code goes here.
                        try {
                            startButton.setEnabled(false);
                            startButton.setVisible(false);
//                            buttonsPanel.setEnabled(false);
//                            buttonsPanel.setVisible(false);
                            expText.setText(settings.getProperty("instructions").toString());

                            resultButtonGroup.clearSelection();
                            deselectButtons(resultButtonGroup);
                            //buttonsPanel.setVisible(true);
                            buttonsPanel.setEnabled(false);

                            scaleLabel.setVisible(false);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                });
                t2.start();



                Thread t1 = new Thread(new Runnable() {
                    public void run() {
                        // code goes here.
                        try {
                            mediaPlayer();
//                               Thread.sleep(5000);


                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                });
                t1.start();

                ActionListener taskPerformer = new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        //...Perform a task...

                        greyButtons(resultButtonGroup);
                        resultButtonGroup.clearSelection();
                        startButton.setEnabled(true);
                        startButton.setVisible(true);
                        buttonsPanel.setVisible(true);
                        scaleLabelText.setVisible(true);
                        enjoyment.setVisible(true);

                        enableButtons(resultButtonGroup);

                        resultButtonGroup.clearSelection();

                        //System.out.println("Reading SMTP Info.");
                    }
                };

                buttonsPanel.setVisible(true);
                scaleLabelText.setVisible(true);
                enjoyment.setVisible(true);
                deselectButtons(resultButtonGroup);
                Timer timer = new Timer(stimDuration, taskPerformer);
                timer.setRepeats(false);
                timer.start();


                //change the state of the experiment
                experimentState++;


            }

            } else if (experimentState == -1) {
                //System.out.print("c");

                buttonsPanel.setVisible(false);
                scaleLabelText.setVisible(false);
                enjoyment.setVisible(false);
                testPhase = false;


                //say: get ready
                expText.setText(settings.getProperty("startExp").toString());
                startButton.setText("Continue");
                scaleLabel.setVisible(false);

                //change the state of the experiment
                experimentState++;
            }

            //if startstate
            else if (experimentState == 0) {

                //start the real experiment

                testPhase = false;

                //say: get ready
                //expText.setText(settings.getProperty("initial").toString());
                startButton.setText("Continue");
                scaleLabel.setVisible(false);

                //change the state of the experiment
                experimentState++;

            }
        if (experimentState > 0) {


                //if it's not the first window
                if (experimentState <= (numberOfInstances * 2 + 0)) {
                    //and it's not passed the last instance


                    //even experiment state (first screen of a stimuli)
                    if (experimentState % 2 != 0) {



                        if ((resultButtonGroup.getSelection() == null) && buttonsPanel.isVisible() == true) {
                            //don't do anything
                            //when radiobuttons not pressed count back timer and say select or do nothing


                        } else {

                            if (experimentState < 2) {
                                expText.setText(settings.getProperty("ready1st").toString());
                            } else {
                                expText.setText(settings.getProperty("ready").toString());

                            }

                            //if it's the first screen: ask if ready
                            buttonsPanel.setVisible(false);
                            scaleLabelText.setVisible(false);
                            enjoyment.setVisible(false);
                            //buttonsPanel.setEnabled(false);

                            if (resultButtonGroup.getSelection() != null) {
                                //GET THE VALUES AND STORE THEM
                                //System.out.print(getSelectedButtonText(resultButtonGroup));
                                if (experimentState != 1) {
                                    addtoResults();
                                }
                                //results.add(Integer.valueOf(resultButtonGroup.getSelection()));
                                //change the state of the experiment
                                experimentState++;
                                instanceNumber++;
                            }


                        }

                        if (experimentState == 1) {
                            experimentState++;
                        }


                    }
                    //uneven experiment state (second screen of a stimuli)s
                    //play sound and display rating buttons after a while
                    else {
                        //else: play sound

                        Thread t2 = new Thread(new Runnable() {
                            public void run() {
                                // code goes here.
                                try {
                                    startButton.setEnabled(false);
                                    startButton.setVisible(false);
//                                    buttonsPanel.setEnabled(false);
//                                    buttonsPanel.setVisible(false);
                                    expText.setText(settings.getProperty("instructions").toString());

                                    resultButtonGroup.clearSelection();

                                    scaleLabelText.setVisible(true);
                                    enjoyment.setVisible(true);
                                    buttonsPanel.setVisible(true);
                                    buttonsPanel.setEnabled(false);
                                    greyButtons(resultButtonGroup);
                                    deselectButtons(resultButtonGroup);

                                    scaleLabel.setVisible(false);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            }
                        });
                        t2.start();


                        Thread t1 = new Thread(new Runnable() {
                            public void run() {
                                // code goes here.
                                try {
                                    mediaPlayer();
//                               Thread.sleep(5000);


                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            }
                        });
                        t1.start();

                        ActionListener taskPerformer = new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                //...Perform a task...

                                resultButtonGroup.clearSelection();

                                startButton.setEnabled(true);
                                startButton.setVisible(true);
                                buttonsPanel.setVisible(true);
                                scaleLabelText.setVisible(true);
                                enjoyment.setVisible(true);

                                enableButtons(resultButtonGroup);
                                resultButtonGroup.clearSelection();



                                //System.out.println("Reading SMTP Info.");
                            }
                        };
                        deselectButtons(resultButtonGroup);
                        resultButtonGroup.clearSelection();
                        Timer timer = new Timer(stimDuration, taskPerformer);
                        timer.setRepeats(false);
                        timer.start();


                        //change the state of the experiment
                        experimentState++;

                    }
                } else {
                    //           if (experimentState > numberOfInstances * 2 + 1){
                    expText.setText(settings.getProperty("thanks").toString());
                    scaleLabel.setVisible(false);
                    buttonsPanel.setVisible(false);
                    scaleLabelText.setVisible(false);
                    enjoyment.setVisible(false);
                    startButton.setVisible(false);


                    //capture last results:

                    if (resultButtonGroup.getSelection() != null) {
                        //GET THE VALUES AND STORE THEM
                        //System.out.print(getSelectedButtonText(resultButtonGroup));
                        //don't store the first read, that will still be the test run
                        if (experimentState != 1) {
                            addtoResults();
                        }
                        //results.add(Integer.valueOf(getSelectedButtonText(resultButtonGroup)));
                        instanceNumber++;
                        //results.add(Integer.valueOf(resultButtonGroup.getSelection()));

                    }




                    //write the last result
                    played.add(instanceNumber);
//            for (int i = 0; i < results.size()-1; i++) {
                    int i = results.size()-1;
                    //todo, put right length
                    out.println(participantNumber + ", " + results.get(i) + ", " + inputList.get(i)[0] + ", " + inputList.get(i)[1] + ", " + inputList.get(i)[2] + ", " + inputList.get(i)[3] + ", " + inputList.get(i)[4] + ", " + inputList.get(i)[5] + ", " + inputList.get(i)[6] + ", " + inputList.get(i)[7]);
//            }
                    out.flush();
                    //close the file
                    out.close();
                    //change the state of the experiment
                    experimentState++;
                }
            }
        }



      //System.out.println("state: " + experimentState);





    public String getSelectedButtonText(ButtonGroup buttonGroup) {
        for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();

            if (button.isSelected()) {
                return button.getText();
            }
        }

        return null;
    }



    public String greyButtons(ButtonGroup buttonGroup) {
        for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();
            button.setForeground(Color.LIGHT_GRAY);


//                JRadioButton button1 = new JRadioButton("<html><p style=\"text-align:right;\"><br>1<br>Did not enjoy</html>");
//            button1.setIconTextGap(-60);
//            JRadioButton button2 = new JRadioButton("2");
//            JRadioButton button3 = new JRadioButton("3");
//            JRadioButton button4 = new JRadioButton("4");
//            JRadioButton button5 = new JRadioButton("5");
//            JRadioButton button6 = new JRadioButton("6");
//            JRadioButton button7 = new JRadioButton("<html><br>7<br>Greatly enjoyed</html>");

        }

        scaleLabelText.setForeground(Color.lightGray);
        enjoyment.setForeground(Color.lightGray);

        return null;
    }


    public String enableButtons(ButtonGroup buttonGroup) {
        for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();
            button.setSelected(false);
            button.setForeground(Color.black);
            button.setEnabled(true);


        }

        scaleLabelText.setForeground(Color.black);
//        enjoyment.setForeground(Color.black);
        enjoyment.setForeground(Color.darkGray);

        return null;
    }


    public void addtoResults(){
        String result = getSelectedButtonText(resultButtonGroup);



        if (result == "<html><p style=\"text-align:right;\"><br>1<br>Did not enjoy</html>"){
            results.add(1);
        }
        else if (result ==   "<html><br>7<br>Greatly enjoyed</html>"){
            results.add(7);
        }
        else {
            results.add(Integer.valueOf(result));
        }


    }


    public String deselectButtons(ButtonGroup buttonGroup) {
        for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();
            //button.setSelected(false);
            //button.setForeground(Color.black);
            button.setEnabled(false);
            button.setSelected(false);

        }
        scaleLabelText.setForeground(Color.lightGray);
        enjoyment.setForeground(Color.lightGray);

        return null;
    }

    /**
     * Read in the config file
     */
    public void readConfig() throws IOException {

        InputStream input = null;
        input = new FileInputStream("settings.conf");

        // load a properties file
        settings.load(input);

        if (settings.getProperty("test").equals("y")) {
            testMode = true;
        }
        else {
            testMode = false;
        }

        // get the property value and print it out
        //System.out.println(settings.getProperty("welcome"));
    }


    public void runExperiment() throws IOException {




        //configure layout

        this.setVisible(true);
        JPanel contentPanel = new JPanel(new GridBagLayout());
        this.add(contentPanel);

        testPhase = true;

        //set Title

        titleText = new JLabel(settings.getProperty("title").toString(), SwingConstants.CENTER);
        titleText.setFont(new Font("Arial", Font.PLAIN, 20));
        //ex.add(titleText);



        //set start explanation

        expText = new JLabel("", SwingConstants.CENTER);
        //expText.setPreferredSize(new Dimension(200, 140));
        expText.setVisible(true);

        instructionsText = new JLabel(settings.getProperty("welcome").toString(), SwingConstants.CENTER);
        //expText.setPreferredSize(new Dimension(200, 140));
        //instructionsText.setVisible(true);

        //expText.setLayout(null);

        scaleLabel = new JLabel("", SwingConstants.CENTER);
        scaleLabel.setVisible(false);

        participantText = new JLabel(settings.getProperty("number").toString(), SwingConstants.CENTER);
        //expText.setPreferredSize(new Dimension(200, 140));
        participantText.setVisible(true);



        userNumber = new JLabel("", SwingConstants.CENTER);
        userNumber.setFont(new Font("Helvetica", Font.PLAIN, 8));
        //expText.setPreferredSize(new Dimension(150, 40));

        //get a text box to input participantNumber
        userText = new JTextField(4);
        userText.setPreferredSize(new Dimension(60,20));


        //start Button
        startButton = new JButton("Start");
        startButton.setPreferredSize(new Dimension(100, 40));
        startButton.addActionListener(this);


        // set radio buttons
//        JRadioButton button1 = new JRadioButton("<html><p style=\"text-align:right;\"><br>1<br>Did not enjoy</html>");
//        button1.setIconTextGap(-60);
        JRadioButton button2 = new JRadioButton("2");
        JRadioButton button3 = new JRadioButton("3");
        JRadioButton button4 = new JRadioButton("4");
        JRadioButton button5 = new JRadioButton("5");
        JRadioButton button6 = new JRadioButton("6");
//        JRadioButton button7 = new JRadioButton("<html><br>7<br>Greatly enjoyed</html>");
        JRadioButton button1 = new JRadioButton("1");
        JRadioButton button7 = new JRadioButton("7");
        scaleLabelText = new JLabel("  (Not at all)                         (Moderate)                        (Very much)", SwingConstants.CENTER);
        enjoyment = new JLabel("Enjoyment", SwingConstants.CENTER);

        button1.setMargin(new Insets(5, 5, 0, 10));
        button2.setMargin(new Insets(5, 5, 0, 10));
        button3.setMargin(new Insets(5, 5, 0, 10));
        button4.setMargin(new Insets(5, 5, 0, 10));
        button5.setMargin(new Insets(5, 5, 0, 10));
        button6.setMargin(new Insets(5, 5, 0, 10));
        button7.setMargin(new Insets(5, 5, 0, 10));


        scaleLabelText.setForeground(Color.lightGray);
        enjoyment.setForeground(Color.lightGray);
        scaleLabelText.setVisible(false);
        enjoyment.setVisible(false);

        resultButtonGroup = new ButtonGroup();
        resultButtonGroup.add(button1);
        button1.setBackground(Color.white);
        resultButtonGroup.add(button2);
        button2.setBackground(Color.white);
        resultButtonGroup.add(button3);
        button3.setBackground(Color.white);
        resultButtonGroup.add(button4);
        button4.setBackground(Color.white);
        resultButtonGroup.add(button5);
        button5.setBackground(Color.white);
        resultButtonGroup.add(button6);
        button6.setBackground(Color.white);
        resultButtonGroup.add(button7);
        button7.setBackground(Color.white);




        // Create a panel to group the buttons.
        buttonsPanel = new JPanel();
        buttonsPanel.setBackground(Color.white);
        // Add all of the buttons in the group to the panel.
        for (Enumeration<AbstractButton> en = resultButtonGroup.getElements(); en.hasMoreElements(); ) {
            AbstractButton b = en.nextElement();
            buttonsPanel.add(b);
        }
        greyButtons(resultButtonGroup);


        ImageIcon icon = new ImageIcon("./scale.png");
        scaleLabel.setIcon(icon);



        expText.setFont(new Font("Helvetica", Font.PLAIN, 16));
        instructionsText.setFont(new Font("Helvetica", Font.PLAIN, 16));
        buttonsPanel.setFont(new Font("Helvetica", Font.PLAIN, 16));
        enjoyment.setFont(new Font("Helvetica", Font.PLAIN, 20));
        scaleLabelText.setFont(new Font("Helvetica", Font.PLAIN, 14));
        userText.setFont(new Font("Helvetica", Font.PLAIN, 16));
        startButton.setFont(new Font("Helvetica", Font.PLAIN, 16));
        participantText.setFont(new Font("Helvetica", Font.PLAIN, 16));



        //startButton.setBounds(10,10,250,100);
        startButton.setSize(100, 20);


        instructionsText.setVisible(false);
        contentPanel.setBackground(Color.white);

        contentPanel.add(titleText, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.HORIZONTAL, new Insets(80, 100, 0, 100), 0, 0));
        contentPanel.add(expText, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.CENTER, new Insets(-560, 100, 00, 100), 0, 0));
        contentPanel.add(instructionsText, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.CENTER, new Insets(150, 100, 00, 100), 0, 0));
//        contentPanel.add(expText, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
//                GridBagConstraints.CENTER, new Insets(-600, 100, 00, 100), 0, 0));
//        contentPanel.add(scaleLabel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
//                GridBagConstraints.CENTER, new Insets(560, 100, 00, 100), 0, 0));

        contentPanel.add(enjoyment, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.HORIZONTAL, new Insets(-408, 100, 0, 100), 0, 0));
        contentPanel.add(buttonsPanel, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.HORIZONTAL, new Insets(-370, 100, 0, 100), 0, 0));
        contentPanel.add(scaleLabelText, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.HORIZONTAL, new Insets(-300, 100, 0, 100), 0, 0));


//        contentPanel.add(participantText, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
//                GridBagConstraints.CENTER, new Insets(-220, 0, 0, 0), 0, 0));
        contentPanel.add(userText, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.CENTER, new Insets(-180, 0, 0, 0), 0, 0));
        contentPanel.add(startButton, new GridBagConstraints(0, 3, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
                GridBagConstraints.CENTER, new Insets(-120, 0, 0, 0), 0, 0));

        contentPanel.add(Box.createVerticalGlue(), new GridBagConstraints(0, 1, 2, 2, 1, 1,
                GridBagConstraints.PAGE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

//        contentPanel.add(userNumber, new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.PAGE_START,
//                GridBagConstraints.CENTER, new Insets(340, 0, 0, 0), 0, 0));

        buttonsPanel.setVisible(false);
        scaleLabelText.setVisible(false);
        enjoyment.setVisible(false);





        //write data
        //last result of test is accidentally stored, compensate for this
//        for (int i = 0; i < results.size()-1; i++) {
//            //todo, put right length
//            out.println(participantNumber + ", " + results.get(i+1) + ", " + inputList.get(i)[0] + ", " + inputList.get(i)[1] + ", " + inputList.get(i)[2] + ", " + inputList.get(i)[3] + ", " + inputList.get(i)[4] + ", " + inputList.get(i)[5] + ", " + inputList.get(i)[6]+ ", " + inputList.get(i)[7]);
//        }


//
//        this.setFocusable(true);
//        addMouseListener(new MouseAdapter() {
//
//            @Override
//            public void mouseClicked(MouseEvent e) {
//                requestFocusInWindow();
//            }
//
//        });
//
//        this.addKeyListener(new KeyAdapter() {
//
//            @Override
//            public void keyPressed(KeyEvent e) {
//                if (e.getKeyCode() == KeyEvent.VK_K && e.getKeyCode() == KeyEvent.VK_A) {
//
//                    expText.setText("ok");
//                    JOptionPane.showMessageDialog(expText, "message") ;
//                }
//            }
//
//        });




        //Read in the stimuli list
        readCSV();
        testNumber = 0;
        numberOfInstances = inputList.size();

        //randomise the list
        randomizeInput();

        //feed it to the program
        instanceNumber = 0;






    }


    public void readCSV() {

        String csvFile = "./input.csv";
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        inputList = new ArrayList<String[]>();

        try {

            br = new BufferedReader(new FileReader(csvFile));
            int i = 0;
            while ((line = br.readLine()) != null) {


                // use comma as separator
                String[] inputLine = line.split(cvsSplitBy);

//                System.out.println(inputLine[0] + " " + inputLine[1] + " " +inputLine[2] +" " + inputLine[3]
//                        + " " + inputLine[4]);

                if (i == 0){
                   header = inputLine.clone();
                }
                else{
                    inputList.add(inputLine);

                }
                i++;

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }



    public void randomizeInput(){
        long seed = System.nanoTime();
        Collections.shuffle(inputList, new Random(seed));

//        for (String[] inputLine : inputList) {
//            System.out.println(inputLine[0] + " " + inputLine[1] + " " + inputLine[2] + " " + inputLine[3]
//                    + " " + inputLine[4]);
//        }
    }



    public static void main(String[] args) {


        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {


                //Set the basic layout

                TranceExperiment ex = null;
                try {
                    ex = new TranceExperiment();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                try {
                    ex.runExperiment();
                } catch (IOException e) {
                    e.printStackTrace();
                }





            }

        });
    }
}