package clientIHM;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

import clientIHM.ChatterIHM.SessionState;

import chat.*;

public class GestChatRoomIHM extends JDialog implements ActionListener {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	GestTopics gt;
	JList topicsList;
	JButton joinButton;
	JButton refreshButton;
	JTextField topicField;
	JButton createButton;
	private ChatterIHM chatterIHM;

	public GestChatRoomIHM (GestTopics gt, ChatterIHM chatterIHM) {
		setTitle("Choix topic");
		this.setSize(400,300);
		this.gt = gt;
		this.chatterIHM = chatterIHM;
		// buttons
		refreshButton = new JButton("Refresh");
		refreshButton.addActionListener(this);
		joinButton = new JButton("Join");
		joinButton.addActionListener(this);
		
		JPanel buttonsZone= new JPanel();
		buttonsZone.add(joinButton);
		buttonsZone.add(refreshButton);
		
		JPanel topicsZone = new JPanel();
		topicsList = new JList();
		topicsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION );
		
		topicsZone.add(topicsList);
		topicsZone.add(buttonsZone);
		this.add(topicsZone,"Center");
		// textfields
		JPanel createZone=new JPanel();
		topicField = new JTextField (20);
		createZone.add(topicField);
		createButton = new JButton("Create topic");
		createButton.addActionListener(this);
		createZone.add(createButton);
		this.add(createZone,"South");
	}

	@Override
	public void setVisible (boolean mode) {
		if (mode)
			topicsList.setListData(gt.listerTopics());
		super.setVisible(mode);
	}
	
	public void actionPerformed(ActionEvent ev) {
		if (ev.getSource() == refreshButton) {			
			topicsList.setListData(gt.listerTopics());
		} else if (ev.getSource() == joinButton) {
			ChatRoom cr = gt.rejoindreTopic(topicsList.getSelectedValue().toString());
			chatterIHM.setChatRoom(cr);
			cr.rejoindre(chatterIHM);
			chatterIHM.setState(SessionState.CHATTING);
			this.setVisible(false);
			//System.out.println("coucou"+topics.getSelectedValue());
		} else if (ev.getSource() == createButton ) {
			gt.creerTopic(topicField.getText());
			//topicsList.add(topicField.getText());
		}
	}

}
