//   Course Number: COSC 650 Data Comm/Networks
//      Class Name: ChatroomDialog.java
//  Project Number: 2
//         Authors: Brian Hoffman
//                  Mike McKinney
//                  Javier Carrasco
//     Description: This file contains the JDialog used to represent each chatroom.
//                  JDialogs were chosen because they are tied to the main window
//                  and share its look and feel, icon, and are minimized or closed 
//                  whenever it is. This allows the master program window to contol
//                  all the individual chatrooms.
// 
//                  The chatroom dialog contains a JList of chatroom participants,
//                  a message output area, and a compose message area. The JList of
//                  participants is updated by the main MultiChatClient through
//                  the addParticipant() and removeParticipant() methods when it
//                  receives the appropriate messages from the server. The message
//                  output area is accessed by the MultiChatClient class through 
//                  the postMessage() method and is used to display all default 
//                  messages designated for that room. The compose message area 
//                  is used to write messages for the other chatroom participants.
//                  It contains a JTextArea, a send button, and a clear button. 
//                  The send button uses the MultiChatClient's sendMessage() method
//                  to send the message in the JTextArea. The clean button simply 
//                  clears the compose message's JTextArea.
//
//                  Finally, the chatroom contains two buttons for interacting with
//                  participants. The boot button is only enabled for the room owner
//                  and it sends a message to the server kicking the chosen person 
//                  from the room. The request private button makes it possible for 
//                  two users in a room to create a separate private room. It does 
//                  this through an exchange of messages with the server -- see
//                  ChatMessage.java

// Java Core Packages
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.Vector;

// Jave Extension Packages 
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

public class ChatroomDialog extends JDialog
{ 
   // private class variables
   Container container;
   MultiChatClient client;
   String roomType;                            
   String roomName;             
   String roomOwner;
   DefaultListModel participants;

   // Simple GUI components
   JPanel labelPanel;
   JLabel roomNameLabel;
   JLabel roomOwnerLabel;
   GriddedPanel mainPanel;
   
   // The participant's Panel
   GriddedPanel participantPanel;
   JList participantList;
   JButton privateButton;
   JButton bootButton;
   
   // The messages panel
   JPanel messagesPanel;
   JPanel chatPanel;
   JTextArea msgOutputArea;
   GriddedPanel composePanel;
   JTextArea msgInputArea;
   JButton sendButton;
   JButton clearButton;

    /**
     * ------------------------------------------------------------------------
     * constructor - sets up the GUI
     * ------------------------------------------------------------------------
     */
    public ChatroomDialog(MultiChatClient inClient, String inType, String inName,
                          String inOwner, Vector inParticipants)
    {   
        // set the instance variables
        super(inClient, "User: " + inClient.getUserName() +
                        "     Chatroom: " + inName);
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        addWindowListener(new winClosingHandler());
        client = inClient;
        roomType = inType;
        roomName = inName;
        roomOwner = inOwner;
        
        // get the content pane and set layout 
        container = getContentPane();
        container.setLayout(new BorderLayout());
        mainPanel = new GriddedPanel();
        container.add(mainPanel, BorderLayout.CENTER);
        
        // create the two labels at the top
        roomNameLabel = new JLabel("Chatroom Name: " + roomName);
        roomOwnerLabel = new JLabel("Chatroom Owner: " + roomOwner);
        mainPanel.addComponent(roomNameLabel, 1, 1);
        mainPanel.addComponent(roomOwnerLabel, 2, 1);       

        // create the participant JList and list model
        participants = new DefaultListModel();
        for (int i=0; i<inParticipants.size(); i++)
        {
            participants.addElement(inParticipants.get(i));
        }     
        participantList = new JList(participants);
        participantList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // create the participants panel
        participantPanel = new GriddedPanel(); 
        privateButton = new JButton("Chat Privately");
        privateButton.addActionListener(new privateButtonHandler());
        bootButton = new JButton("Remove");
        if (!client.getUserName().equals(roomOwner))
        { bootButton.setEnabled(false); }
        bootButton.addActionListener(new bootButtonHandler());
        participantPanel.setBorder(BorderFactory.createTitledBorder(
                       BorderFactory.createEtchedBorder(), "Participants Panel",
                       TitledBorder.LEFT, TitledBorder.TOP )); 
        participantPanel.addFilledComponent(new JScrollPane(participantList),
                                            1, 1, 2, 2, GridBagConstraints.BOTH);
        if (roomType.equals("public"))
        {
            participantPanel.addComponent(privateButton, 3, 1);
            participantPanel.addComponent(bootButton, 3, 2);
        }
        mainPanel.addFilledComponent(participantPanel, 3, 1, 1, 3,
                                     GridBagConstraints.BOTH);
        
        // create the messages panel 
        messagesPanel = new JPanel();
        messagesPanel.setLayout(new BorderLayout());
        
        // build the chatPanel that goes on the messages panel
        chatPanel = new JPanel();
        chatPanel.setLayout(new BorderLayout());
        chatPanel.setBorder(BorderFactory.createTitledBorder(
                      BorderFactory.createEtchedBorder(), "Chat Messages Panel",
                      TitledBorder.LEFT, TitledBorder.TOP )); 
        msgOutputArea = new JTextArea(15, 30);
        chatPanel.add(new JScrollPane(msgOutputArea), BorderLayout.CENTER);
        messagesPanel.add(chatPanel, BorderLayout.CENTER);
        
        // create the compose message panel that goes on the message panel
        composePanel = new GriddedPanel();
        msgInputArea = new JTextArea(4, 20);
        sendButton = new JButton("Send");
        sendButton.addActionListener(new sendButtonHandler());
        clearButton = new JButton("Clear");
        clearButton.addActionListener(new clearButtonHandler());
        composePanel.setBorder(BorderFactory.createTitledBorder(
                           BorderFactory.createEtchedBorder(), 
                           "Compose Messages Panel",
                           TitledBorder.LEFT, TitledBorder.TOP ));
        composePanel.addFilledComponent(new JScrollPane(msgInputArea),
                                     1, 1, 2, 2, GridBagConstraints.BOTH);
        composePanel.addComponent(sendButton, 1, 3);
        composePanel.addComponent(clearButton, 2, 3);
        messagesPanel.add(composePanel, BorderLayout.SOUTH);
        
        //add the messages panel to the main panel
        mainPanel.addFilledComponent(messagesPanel, 1, 2, 3, 5,
                                     GridBagConstraints.BOTH);
        
        pack();
        setVisible(true);
    }  

    /**
     * ------------------------------------------------------------------------
     * privateButtonHandler
     * ------------------------------------------------------------------------
     */
    private class privateButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            ChatMessage msg = new ChatMessage("requestPrivate", client.getUserName(), 
                              "", (String) participantList.getSelectedValue());
            client.sendMessage(msg);
        }
    } 
    
    /**
     * ------------------------------------------------------------------------
     * bootButtonHandler
     * ------------------------------------------------------------------------
     */
    private class bootButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            // don't let the owner boot themselves
            if(participantList.getSelectedValue().equals(client.getUserName()))
               return;
            ChatMessage bootMsg = new ChatMessage("bootUser", client.getUserName(),
                            roomName, (String) participantList.getSelectedValue());
            client.sendMessage(bootMsg);
        }
    } 
    
    /**
     * ------------------------------------------------------------------------
     * sendButtonHandler
     * ------------------------------------------------------------------------
     */
    private class sendButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            ChatMessage msg = new ChatMessage("default", client.getUserName(),
                                              roomName, msgInputArea.getText());
            client.sendMessage(msg);
            msgInputArea.setText("");
        }
    } 
    
    /**
     * ------------------------------------------------------------------------
     *  clearButtonHandler
     * ------------------------------------------------------------------------
     */
    private class clearButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            msgInputArea.setText("");
        }
    }
    
    /**
     * ------------------------------------------------------------------------
     *  winClosingHandler - handle it when the user leaves by closing the window
     * ------------------------------------------------------------------------
     */
    private class winClosingHandler extends WindowAdapter
    {
        public void windowClosing(WindowEvent event)
        {
            // send a leaveRoom messgage
            ChatMessage msg = new ChatMessage("leaveRoom", client.getUserName(),
                                              roomName, "");
            client.sendMessage(msg);

            // if I am the owner, remove it from the roomSelectList
            if (roomOwner.equals(client.getUserName()))
            { client.removeFromRoomList(roomName); }
            
            // tell the main program I am closing 
            client.dialogClosing(roomName);

            // dispose of myself 
            dispose();
        }
    } 
    
    /**
     * ------------------------------------------------------------------------
     * addParticipant - add a new participant to the JList
     * ------------------------------------------------------------------------
     */
    public void addParticipant(String nickname)
    {
        participants.addElement(nickname);
    }
    
    
    /**
     * ------------------------------------------------------------------------
     * removeParticipant - remove a participant from the JList
     * ------------------------------------------------------------------------
     */
    public void removeParticipant(String nickname)
    {
        int pos;
        String temp;
        
        for(pos=0; pos<participants.getSize(); pos++)
        {
            temp = (String) participants.getElementAt(pos);
            if (temp.equals(nickname)) break;
        }
        if(pos == participants.getSize()) return;
        participants.removeElementAt(pos);
    }
    
    /**
     * ------------------------------------------------------------------------
     * displayMessage - sisplay a message in the output area
     * ------------------------------------------------------------------------
     */
    public void displayMessage(ChatMessage msg)
    {
        msgOutputArea.append(msg.getSender() + ": " + msg.getMsg() + "\n");
        msgOutputArea.setCaretPosition(msgOutputArea.getText().length());
    }
}  