import java.awt.*;

import javax.swing.*;
import java.awt.event.*;

class SudokuUI extends JPanel implements ActionListener 
{
  private SudokuCanvas  _canvas; 
  private JTextField    _fldLineCoor;
  private JTextField    _fldColCoor;
  private JTextField    _fldMove;
  private JButton       _btnDraw;
  
  public SudokuUI(int[][] matrice, boolean[][] contraintes) 
  {
    // create the GUI components
    _canvas = new SudokuCanvas(matrice, contraintes);  
    _canvas.setBackground(Color.white);
    _canvas.setPreferredSize(new Dimension(362, 362));
    
    _fldLineCoor = new JTextField(3);
    _fldColCoor = new JTextField(3);
    _btnDraw = new JButton("Verify!");  // 
    _fldMove = new JTextField(3);
    _btnDraw.addActionListener(this);
    
    JPanel topHalf = new JPanel();
    JPanel bottomHalf = new JPanel();
    
    // layout the top half
    topHalf.setLayout(new FlowLayout());
    topHalf.add(_canvas);
    
    // layout the bottom half
    bottomHalf.setLayout(new FlowLayout());
    bottomHalf.add(new JLabel("Row"));   // Row
    bottomHalf.add(_fldLineCoor);
    bottomHalf.add(new JLabel("Column")); // Column
    bottomHalf.add(_fldColCoor);
    bottomHalf.add(new JLabel("Guess (0-9)"));   // Guess    
    bottomHalf.add(_fldMove);
    bottomHalf.add(_btnDraw);
    
    // layout overall GUI
    setLayout(new BorderLayout());
    add(topHalf, "North");
    add(bottomHalf, "South");
  }
  
  public void actionPerformed(ActionEvent evt) 
  {   
    int pos = 0;
    char car;
    int l = 0;
    int c = 0;
    int move = 0;
    boolean withinRange = false;
    boolean allNumbers = true;
    
    String text = _fldLineCoor.getText() + _fldColCoor.getText() + _fldMove.getText();
    for (pos = 0; (pos < text.length() && allNumbers); pos = pos + 1)
    {
      car = text.charAt(pos);
      allNumbers = (allNumbers && car >= '0' && car <= '9');
    }
    
    if (allNumbers)
    {
      try 
      {
        l = Integer.parseInt(_fldLineCoor.getText());
        c = Integer.parseInt(_fldColCoor.getText());
        move = Integer.parseInt(_fldMove.getText());
        withinRange = (l >= 1 && l <= 9 && c >=1 && c <=9 && move >=0 && move <=9);
      }
      catch (java.lang.NumberFormatException e)
      {
        withinRange = false;
      }
    }
    
    if (withinRange && allNumbers) 
    {
      _canvas.updateMove(l, c, move);
      _fldMove.setText("");  
      _fldLineCoor.setText("");
      _fldColCoor.setText("");  
    }
    else
    {
      JOptionPane.showMessageDialog(null, "Invalid entry! (1-9 for row and column, 0-9 for the guess)"); // ENGLISH
    }
  } 
  
}
