package industries.doublehelix.furrynotemanager.gui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import industries.doublehelix.furrynotemanager.Site;
import layout.TableLayout;

public class CaptchaDialog extends JDialog implements ActionListener {
	private static final long serialVersionUID = 6043272317508195684L;
	JButton ok = new JButton("OK");
	JButton abort = new JButton("Abort");
	JTextField captchaText = new JTextField();
	String captcha = null;
	
	
	public CaptchaDialog(Component parent, Site site, BufferedImage image) {
		this.setSize(new Dimension(200, 200));
		this.setTitle("Captcha from " + site.getName());
		this.setLocationRelativeTo(parent);
		this.setModal(true);
		this.setResizable(false);
		
		JPanel mainPanel = new JPanel();
		mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
		double sizeSettings[][] = {{TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED}, //width
				{TableLayout.PREFERRED, 10, TableLayout.FILL, 10, TableLayout.PREFERRED, 10, TableLayout.PREFERRED}}; // height
		mainPanel.setLayout(new TableLayout(sizeSettings));
		
		JLabel label = new JLabel("<html><body>Please enter below's Captcha for " + site.getName() + "</body></html>");
		JLabel imageLabel = new JLabel(new ImageIcon(image));

		ok.addActionListener(this);
		captchaText.addActionListener(this);
		abort.addActionListener(this);
		
		mainPanel.add(label, "0, 0, 2, 0");
		mainPanel.add(imageLabel, "0, 2, 2, 2");
		mainPanel.add(captchaText, "0, 4, 2, 4");
		mainPanel.add(ok, "0, 6");
		mainPanel.add(abort, "2, 6");
		
		
		this.add(mainPanel);
		
		
		this.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == ok || e.getSource() == captchaText) {
			captcha = captchaText.getText();
			this.dispose();
		} else {
			this.dispose();
		}
	}

	/**
	 * null if user aborted
	 * @return null if user aborted
	 */
	public String getCaptcha() {
		return captcha;
	}
}
