import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;

/**
  *
  * Beschreibung
  *
  * @version 1.0 vom 26.05.2017
  * @author 
  */

public class ChatServerGUI extends JFrame implements MyServerSocketListener  {
  // Anfang Attribute
  private ArrayList<MySocket> clients;
  private ArrayList<String> names;
  private static boolean ende;
  private MyServer server;
  private JLabel jLabel1 = new JLabel();
  private JButton jBStarten = new JButton();
  private JNumberField jNFPort = new JNumberField();
  private JList jList1 = new JList();
  private DefaultListModel jList1Model = new DefaultListModel();
  private JScrollPane jList1ScrollPane = new JScrollPane(jList1);
  private JLabel jLabel2 = new JLabel();
  private int changeClientListAktiv = 0;
  private JLabel jLabel3 = new JLabel();
  // Ende Attribute
   
  public ChatServerGUI() { 
    // Frame-Initialisierung
    super();
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    int frameWidth = 300; 
    int frameHeight = 311;
    setSize(frameWidth, frameHeight);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - getSize().width) / 2;
    int y = (d.height - getSize().height) / 2;
    setLocation(x, y);
    setTitle("Chat-Server");
    setResizable(false);
    Container cp = getContentPane();
    cp.setLayout(null);
    // Anfang Komponenten
    
    jLabel1.setBounds(8, 16, 110, 20);
    jLabel1.setText("Portnummer");
    cp.add(jLabel1);
    jBStarten.setBounds(96, 48, 75, 25);
    jBStarten.setText("Starten");
    jBStarten.setMargin(new Insets(2, 2, 2, 2));
    jBStarten.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent evt) { 
        jBStarten_ActionPerformed(evt);
      }
    });
    cp.add(jBStarten);
    jNFPort.setBounds(128, 16, 99, 20);
    jNFPort.setText("44444");
    cp.add(jNFPort);
    jList1.setModel(jList1Model);
    jList1ScrollPane.setBounds(8, 112, 265, 137);
    cp.add(jList1ScrollPane);
    jLabel2.setBounds(8, 88, 110, 20);
    jLabel2.setText("Chatteilnehmer");
    cp.add(jLabel2);
    addWindowListener(new WindowAdapter() { 
      public void windowClosing(WindowEvent evt) { 
        ChatServerGUI_WindowClosing(evt);
      }
    });
    jLabel3.setBounds(24, 248, 229, 20);
    jLabel3.setText("(cc) 2017, Thomas Schaller, Version 1.0");
    jLabel3.setForeground(Color.GRAY);
    cp.add(jLabel3);
    // Ende Komponenten
    
    setVisible(true);
    
    clients    = new ArrayList<MySocket>();
    names      = new ArrayList<String>();
    server     = null;
    
  } // end of public ChatServerGUI
  
 
  
  // Anfang Methoden
  
  public void neuerClient(MySocket client) {
    for (String n : names) {
      if (!n.equals("ManInTheMiddle")) {
        client.sendeNachricht("user:"+n);
      } // end of if
    } // end of for
    this.clients.add(client);
    //    System.out.println("Habe Kontakt mit "+client.getSocket().getInetAddress()+" Port "+client.getSocket().getPort());
    this.names.add("?");
    //    changeClientList();
  }
  
  public void changeClientList() {
    changeClientListAktiv++;
    if (changeClientListAktiv == 1) {
    do{
      changeClientListAktiv--;
        DefaultListModel newListModel = new DefaultListModel();
        System.out.println("lm: "+jList1Model.size());
        System.out.println("Clients: "+clients.size());
        for (int i = 0; i < clients.size() ; i++ ) {
        MySocket s = clients.get(i);
          String   n = names.get(i);
          newListModel.addElement(n+"("+s.getSocket().getInetAddress()+":"+s.getSocket().getPort()+")");
          System.out.println(n+"("+s.getSocket().getInetAddress()+":"+s.getSocket().getPort()+")");
        System.out.println("lm: "+jList1Model.size());
          } // end of for
        jList1.setModel(newListModel);
        jList1.validate();  
        }
        while (changeClientListAktiv > 0 );
        } // end of if
        }
      
      public void nachrichtEmpfangen(MySocket client) {
    String s = client.holeNachricht();
    System.out.println("Habe Nachricht empfangen:"+s);
    String[] ss = s.split(":");
    int i = clients.indexOf(client);
    
    if (ss[0].equals("exit")) {
    s = s+names.get(i);
    clients.remove(i);
    names.remove(i);
    client.trenneVerbindung();
    for (int j=0; j<clients.size(); j++) {
    MySocket c =  clients.get(j);
    if (c!=client) {
    c.sendeNachricht(s);
    } // end of if
    }
    changeClientList();
    return;
    } 
    
    if (ss[0].equals("user")) {
    names.set(i,ss[1]);
    for (int j=0; j<clients.size(); j++) {
    MySocket c =  clients.get(j);
    if (c!=client) {
    c.sendeNachricht(s);
    } // end of if
    }
    changeClientList();
    return;
    }   
    
    
    
    if (ss[0].equals("mitm")) {
    names.set(i,"ManInTheMiddle");
    changeClientList();
    return;
    }
    
    if (ss[0].equals("mess")) {
    int nextMitM=-1;
    int start=0;
    if (names.get(i).equals("ManInTheMiddle")) {
    start = i+1;
    } 
    
    for (int j=start;j<clients.size() ;j++ ) {
    if (names.get(j).equals("ManInTheMiddle")) {
    nextMitM = j;
    break;
    
    } // end of if
    } // end of for
    if (nextMitM!=-1) {
    MySocket c = clients.get(nextMitM);
    c.sendeNachricht(s);
    } else {
    for (int j=0; j<clients.size(); j++) {
    MySocket c =  clients.get(j);
    if (!ss[1].equals(names.get(j)) && (ss[2].equals("alle") || ss[2].equals(names.get(j))) && !names.get(j).equals("ManInTheMiddle"))  {
    c.sendeNachricht(s);
    } // end of if
    }   
    } // end of if-else
    
    } // end of if
    } // end of if
    
    
    
    
    public void verbindungBeendet(MySocket client) {
    if (clients.contains(client)) {
    
    int i = clients.indexOf(client);
    
    clients.remove(i);
    System.out.println("Verbindung mit "+client.getSocket().getInetAddress()+" Port: "+client.getSocket().getPort()+" verloren.");
    for (MySocket c: clients) {
    if (c!=client) {
    c.sendeNachricht(("exit:"+names.get(i)+":alle"));
    } // end of if
    }
    names.remove(i);
    changeClientList();
    } // end of if
    
    }
    
    
    /*  public static void main (String[] args) {
    new ChatServer(44444);
    
    ende = false;
    while (!ende) {
    try{
    
    Thread.sleep(100);
    }
    catch(Exception e) {
    System.out.println("Error");
    }
    } // end of while
    }
    
    // Anfang Methoden
    */
    
    public static void main(String[] args) {
    new ChatServerGUI();
    } // end of main
    
    public void jBStarten_ActionPerformed(ActionEvent evt) {
    if (jBStarten.getText().equals("Starten")) {
      server = new MyServer(this, this.jNFPort.getInt());
      server.starten();  
      jBStarten.setText("Stoppen");
      jNFPort.setEnabled(false);
      
    } else {
      server.stoppen();
      server = null;
      jBStarten.setText("Starten");        
      jNFPort.setEnabled(true);
    } // end of if-else
    } // end of jBStarten_ActionPerformed
    
  public void ChatServerGUI_WindowClosing(WindowEvent evt) {
    if (server != null) server.stoppen();
  } // end of ChatServerGUI_WindowClosing

    // Ende Methoden
    } // end of class ChatServerGUI
    