package jrummikub.view.impl;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import jrummikub.util.Event;
import jrummikub.util.IEvent;
import jrummikub.view.IQuitWarningPanel;

/**
 * Warning panel to inform users if their actions would end the current game
 */
public class QuitWarningPanel extends JPanel implements IQuitWarningPanel {
	private static final long serialVersionUID = 1L;
	private JButton cancelButton;
	private JButton quitButton;
	private QuitMode quitMode;
	private Event quitEvent = new Event();
	private Event cancelEvent = new Event();
	private JLabel messageLabel;

	/**
	 * Creates new quit warning panel
	 */
	public QuitWarningPanel() {
		setLayout(new GridBagLayout());

		GridBagConstraints c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 0;
		c.weightx = 1;
		c.weighty = 1;
		c.fill = GridBagConstraints.BOTH;
		c.gridwidth = 2;
		c.anchor = GridBagConstraints.CENTER;

		messageLabel = new JLabel();
		messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
		add(messageLabel, c);

		c.gridy = 1;
		c.gridwidth = 1;
		quitButton = createButton("Beenden", quitEvent);
		cancelButton = createButton("Abbrechen", cancelEvent);
		add(cancelButton, c);
		c.gridx = 1;
		add(quitButton, c);

		setBorder(new CompoundBorder(new LineBorder(Color.BLACK),
				new EmptyBorder(10, 10, 10, 10)));
	}

	private JButton createButton(String title, final Event event) {
		JButton button = new JButton(title);
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				event.emit();
			}
		});
		return button;
	}

	@Override
	public void setMode(QuitMode mode) {
		this.quitMode = mode;
		switch (quitMode) {
		case QUIT_PROCESS:
			messageLabel
					.setText("Beim Beenden geht das aktuelle Spiel verloren");
			break;
		case QUIT_GAME:
			messageLabel.setText("Der aktuelle Spielstand geht verloren");
		}
	}

	@Override
	public QuitMode getQuitMode() {
		return quitMode;
	}

	@Override
	public IEvent getQuitEvent() {
		return quitEvent;
	}

	@Override
	public IEvent getCancelEvent() {
		return cancelEvent;
	}
}
