package GUIs;

import Common.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import Matrix2P.*;
/**
 * Author: Max Buegler - max@sarstech.com
 * Date: Sep 29, 2009
 * Time: 6:48:35 PM
 */
public class WegaGUI extends JFrame {
    private JTextField p1a,p2a;
    private JCheckBox singleMatrix;
    private JTextField[][] matrix;
    private JPanel matrixPanel;
    private GameAlgorithm algorithm;
    private JTextField algo;
    private JButton startbutton;
    private JPanel algoPanel;
    private JComboBox algolist;

    public WegaGUI(){
        super("WEGA GUI");
        //super.setSize(700,300);
        super.setLayout(new BorderLayout());
        JPanel topPanel=new JPanel();
        JLabel p1=new JLabel("P1 Actions:");
        p1a=new JTextField("2",2);
        JLabel p2=new JLabel("P2 Actions:");
        p2a=new JTextField("2",2);
        singleMatrix=new JCheckBox("Zero sum game",false);
        startbutton=new JButton("Start");
        startbutton.addActionListener(new StartListener(this));
        topPanel.add(p1);
        topPanel.add(p1a);
        topPanel.add(p2);
        topPanel.add(p2a);
        topPanel.add(singleMatrix);
        //topPanel.add(games);
        topPanel.add(startbutton);
        p1a.addActionListener(new matrixListener());
        p2a.addActionListener(new matrixListener());
        p1a.addKeyListener(new matrixListener());
        p2a.addKeyListener(new matrixListener());
        singleMatrix.addActionListener(new matrixListener());
        super.add(topPanel,BorderLayout.NORTH);
        JPanel mainPanel=new JPanel();
        mainPanel.setLayout(new BorderLayout());
        matrixPanel=new JPanel();
        matrixPanel.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createTitledBorder("Game matrix"),
                        BorderFactory.createEmptyBorder(5,5,5,5)));

        mainPanel.add(matrixPanel,BorderLayout.CENTER);
        algoPanel=new JPanel();
            algoPanel.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Algorithm"),
                            BorderFactory.createEmptyBorder(5,5,5,5)));
            algoPanel.setLayout(new GridBagLayout());
            GridBagConstraints cons=new GridBagConstraints();
            cons.gridx=0;
            cons.gridy=0;
            cons.weightx=0.2;
            cons.weighty=0.5;
            cons.gridheight=1;
            cons.gridwidth=1;
        
            algolist=new JComboBox(new String[]{
                    "Best reply diagram",
                    "Dominated actions",
                    "Fictitious play",
                    "Find probability devices",
                    "Find threat point",
                    "Lemke-Howson algorithm",
                    "Mixed action play",
                    "Regret matching",
                    "Saddle points"});
            algolist.addActionListener(new AlgoListener());
            algoPanel.add(algolist,cons);
            /*JButton choose=new JButton("Select...");
            choose.addActionListener(new SelectListener());
            algoPanel.add(choose,cons);*/
            cons=new GridBagConstraints();
            cons.gridx=1;
            cons.gridy=0;
            cons.weightx=0.5;
            cons.weighty=0.5;
            cons.gridheight=1;
            cons.gridwidth=3;
            cons.fill=GridBagConstraints.HORIZONTAL;
            algo=new JTextField("(None)",40);
            algo.setEditable(false);
            algoPanel.add(algo,cons);
            cons=new GridBagConstraints();
            cons.gridx=4;
            cons.gridy=0;
            cons.weightx=0.2;
            cons.weighty=0.5;
            cons.gridheight=1;
            cons.gridwidth=1;
            JButton settings=new JButton("Settings...");
            settings.addActionListener(new SettingsListener());
            algo.addMouseListener(new SettingsListener());
            algoPanel.add(settings,cons);


        mainPanel.add(algoPanel,BorderLayout.SOUTH);
        super.add(mainPanel,BorderLayout.CENTER);

        algorithm=new NoAlgorithm();
        new AlgoListener().actionPerformed(null);
        setUpMatrixPanel();
        super.setVisible(true);
    }
    class StartListener implements ActionListener{
        private JFrame frame;

        StartListener(JFrame frame) {
            this.frame = frame;
        }

        public void actionPerformed(ActionEvent e) {
            if (startbutton.getText().compareTo("Stop")==0){
                algorithm.stop();
                return;
            }
            int a1=Integer.parseInt(p1a.getText());
            int a2=Integer.parseInt(p2a.getText());
            double[][] p1=new double[a1][a2];
            double[][] p2=new double[a1][a2];
            for (int x=0;x<a1;x++){
                for (int y=0;y<a2;y++){
                    try{
                        if (singleMatrix.isSelected())
                            p1[x][y]=Double.parseDouble(matrix[x][y].getText());
                        else{
                            p1[x][y]=Double.parseDouble(matrix[2*x][y].getText());
                            p2[x][y]=Double.parseDouble(matrix[2*x+1][y].getText());
                        }
                    }
                    catch(Exception ex){
                        JOptionPane.showMessageDialog(frame,"Please enter numeric value into matrix cell "+x+","+y);
                    }
                }
            }
            GameMatrix m=null;
            Main.CON.setText("");
            Main.CONFRAME.setVisible(true);
            if (singleMatrix.isSelected())m=new GameMatrix(p1);
            else m=new GameMatrix(p1,p2);
            final GameMatrix m2=m;
            startbutton.setText("Stop");
            new Thread(){
                public void run(){
                    algorithm.run(m2, new ActionListener(){
                        public void actionPerformed(ActionEvent e) {
                            startbutton.setText("Start");
                        }
                    });
                }
            }.start();
        }
    }
    public void finishAlgo(){

    }
    class UpdateDescriptorListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            algo.setText(algorithm.getDescriptor());
            algoPanel.updateUI();
        }
    }
    class SettingsListener implements ActionListener,MouseListener{
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}

        public void mouseClicked(MouseEvent e) {
            actionPerformed(null);
        }
        
        public void actionPerformed(ActionEvent e) {
            algorithm.settings(new UpdateDescriptorListener());
            algoPanel.updateUI();
        }
    }
    class AlgoListener implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            if (((String)algolist.getSelectedItem()).compareTo("Dominated actions")==0)
                algorithm=new DominatedActions();
            if (((String)algolist.getSelectedItem()).compareTo("Best reply diagram")==0)
                algorithm=new BestReplyDiagram();
            else if (((String)algolist.getSelectedItem()).compareTo("Fictitious play")==0)
                algorithm=new FictitiousPlay();
            else if (((String)algolist.getSelectedItem()).compareTo("Regret matching")==0)
                algorithm=new RegretMatching();
            else if (((String)algolist.getSelectedItem()).compareTo("Saddle points")==0)
                algorithm=new SaddlePoints();
            else if (((String)algolist.getSelectedItem()).compareTo("Mixed action play")==0)
                algorithm=new MixedActionPlay();
            else if (((String)algolist.getSelectedItem()).compareTo("Lemke-Howson algorithm")==0)
                algorithm=new LemkeHowsonAlgorithm();
            else if (((String)algolist.getSelectedItem()).compareTo("Find threat point")==0)
                algorithm=new ThreatPoint();
            else if (((String)algolist.getSelectedItem()).compareTo("Find probability devices")==0)
                algorithm=new FindProbabilityDevice();

            algo.setText(algorithm.getDescriptor());
            algoPanel.updateUI();
        }
    }
    class matrixListener implements ActionListener, KeyListener {
        public void actionPerformed(ActionEvent e) {
            setUpMatrixPanel();
            repaint();
        }

        public void keyTyped(KeyEvent e) {

        }

        public void keyPressed(KeyEvent e) {

        }

        public void keyReleased(KeyEvent e) {
            setUpMatrixPanel();
        }
    }

    class focusListener implements FocusListener{
        private int x,y;

        focusListener(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public void focusGained(FocusEvent e) {
            matrix[x][y].setSelectionStart(0);
            matrix[x][y].setSelectionEnd(matrix[x][y].getText().length());
        }

        public void focusLost(FocusEvent e) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }
    public void setUpMatrixPanel(){
        try{
            int a1=Integer.parseInt(p1a.getText());
            int a2=Integer.parseInt(p2a.getText());
            matrixPanel.removeAll();
            JTextField[][] old=matrix;
            if (singleMatrix.isSelected()){
                matrixPanel.setLayout(new GridLayout(a1,a2));
                matrix=new JTextField[a1][a2];
                for (int x=0;x<a1;x++){
                    for (int y=0;y<a2;y++){
                        JPanel pt=new JPanel();
                        String v="0";
                        if (old!=null&&x<old.length&&y<old[x].length)v=old[x][y].getText();
                        matrix[x][y]=new JTextField(v,2);
                        matrix[x][y].addFocusListener(new focusListener(x,y));
                        pt.add(matrix[x][y]);
                        matrixPanel.add(pt);
                    }
                }
            }
            else {
                matrixPanel.setLayout(new GridLayout(a1,a2));
                matrix=new JTextField[2*a1][a2];
                for (int x=0;x<a1;x++){
                    for (int y=0;y<a2;y++){
                        JPanel pt=new JPanel();
                        String v="0";
                        if (old!=null&&2*x<old.length&&y<old[x].length)v=old[2*x][y].getText();
                        matrix[2*x][y]=new JTextField(v,2);
                        v="0";
                        if (old!=null&&2*x+1<old.length&&y<old[x].length)v=old[2*x+1][y].getText();
                        matrix[2*x+1][y]=new JTextField(v,2);
                        matrix[2*x][y].addFocusListener(new focusListener(2*x,y));
                        matrix[2*x+1][y].addFocusListener(new focusListener(2*x+1,y));
                        pt.add(matrix[2*x][y]);
                        pt.add(new JLabel(","));
                        pt.add(matrix[2*x+1][y]);
                        matrixPanel.add(pt);
                    }
                }
            }
            matrixPanel.updateUI();
            pack();
        }catch(Exception e){}

    }
    public static void main(String[] args){
        new WegaGUI();
    }
}
