package view;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;

import client.ClientTopicsManager;

@SuppressWarnings("serial")
public class TopicsManagerUI extends JDialog implements ActionListener {
	private ClientTopicsManager ctm;
	private JComboBox topics = new JComboBox();
	private JButton refreshButton = new JButton("refresh");
	private JButton joinButton = new JButton("join");
	private JButton cancelButton = new JButton("cancel");
	private MainClient parent;
	
	public TopicsManagerUI(JFrame parent, String title, boolean modal, ClientTopicsManager ctm) {
		super(parent, title, modal);
		this.parent = (MainClient) parent;
		this.ctm = ctm;
		refreshAction();
		initGraphics();
		initListeners();
	}
	
	public void initGraphics() {
		setSize(400,100);
		
		setLayout(new GridLayout(2,1,-1,5));
		
		JPanel buttonsPanel = new JPanel(new FlowLayout());
		buttonsPanel.add(refreshButton);
		buttonsPanel.add(joinButton);
		buttonsPanel.add(cancelButton);
		
		getContentPane().add(Util.getLabeledComponent(topics, "topics"));
		getContentPane().add(buttonsPanel);
	}
	
	public void initListeners() {
		refreshButton.addActionListener(this);
		joinButton.addActionListener(this);
		cancelButton.addActionListener(this);
	}
	
	public void refreshAction() { 
		if (parent.isConnected()) {
			topics.removeAll();
			Vector<String> vect = ctm.listTopics();
			for (int i = 0 ; i < vect.size() ; i++) {
				topics.addItem(vect.get(i));
			}
		} else {
			topics = new JComboBox();
		}
	}

	public void joinAction() {
		if (parent.isConnected()) {
			String selectedTopic = (String) topics.getSelectedItem();
			parent.setCurChatroom(ctm.joinTopic(selectedTopic));
			parent.getCurrentChatroom().join(parent);
		}
		setVisible(false);
	}
	
	public void cancelAction() {
		setVisible(false);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == refreshButton) {
			refreshAction();
		} else if (e.getSource() == joinButton) {
			joinAction();
		} else if (e.getSource() == cancelButton) {
			cancelAction();
		}
	}
}
