package jrummikub.view.impl;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JProgressBar;
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.IConnectPanel;
import jrummikub.view.LoginError;

/**
 * Panel shown during network connecting process and showing errors
 */
public class ConnectPanel extends JPanel implements IConnectPanel {
	private static final long serialVersionUID = 1L;
	private JLabel messageLabel;
	private JProgressBar foobar;
	private JButton cancelButton;

	private Event cancelEvent = new Event();

	/**
	 * Creates new connection panel
	 */
	public ConnectPanel() {
		setLayout(new GridBagLayout());

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

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

		c.gridy = 1;
		c.insets = new Insets(5, 5, 5, 5);

		foobar = new JProgressBar();
		foobar.setIndeterminate(true);
		add(foobar, c);

		c.gridy = 2;

		cancelButton = new JButton();
		cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				cancelEvent.emit();
			}
		});
		add(cancelButton, c);

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

	@Override
	public void setMode(LoginError error) {
		if (error == null) {
			foobar.setVisible(true);
			messageLabel.setText("Verbindung wird hergestellt");
			cancelButton.setText("Abbrechen");
		} else {
			foobar.setVisible(false);
			String text = "";
			switch (error) {
			case UNKNOWN_ERROR:
				text = "Ein unbekannter Fehler ist aufgetreten";
				break;
			case AUTHENTICATION_FAILED:
				text = "Die Authentifizierung ist fehlgeschlagen";
				break;
			case CONNECTION_REFUSED:
				text = "Die Verbindung wurde abgelehnt";
				break;
			case TIMEOUT:
				text = "Der Server reagiert nicht";
				break;
			case UNKNOWN_CHANNEL:
				text = "Der Channel konnte nicht gefunden werden";
				break;
			case UNKNOWN_HOST:
				text = "Der Server konnte nicht gefunden werden";
				break;
			}
			messageLabel.setText(text);
		}
	}

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

}
