Add Registration functionality and tidy up
[WeStealzYourDataz.git] / src / uk / ac / ntu / n0521366 / wsyd / client / ClientGUI.java
index 06daa9c..8fe4601 100644 (file)
@@ -1,7 +1,25 @@
 /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
+ * The MIT License
+ *
+ * Copyright 2015 Eddie Berrisford-Lynch <dev@fun2be.me>.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
  */
 package uk.ac.ntu.n0521366.wsyd.client;
 
@@ -11,6 +29,7 @@ import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.text.MessageFormat;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.SortedMap;
 import javax.swing.JDialog;
@@ -20,9 +39,11 @@ import java.util.TreeSet;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import javax.swing.JProgressBar;
+import javax.swing.ProgressMonitor;
 import javax.swing.Timer;
 import uk.ac.ntu.n0521366.wsyd.libs.WSYD_Member;
 import uk.ac.ntu.n0521366.wsyd.libs.message.MessageLogin;
+import uk.ac.ntu.n0521366.wsyd.libs.message.MessageMember;
 import uk.ac.ntu.n0521366.wsyd.libs.net.Network;
 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessage;
 import uk.ac.ntu.n0521366.wsyd.libs.net.NetworkMessageEvent;
@@ -43,18 +64,24 @@ public class ClientGUI extends javax.swing.JFrame implements NetworkMessageEvent
     
     private boolean loginSuccessful = false;
     
-    private boolean regiSuccessful = false;
+    private boolean registrationSuccessful = false;
+    
+    private final Login loginDialog = new Login(this, true);
+    private final EditProfile registrationDialog = new EditProfile(this, true);
     
-    private Login login = new Login(this, true);
+    /**
+     * Member record for this client's user.
+     */
+    private WSYD_Member myMember;
     
     Socket socialSocket;
     
     /**
      * Readable/displayable name of this application
      * 
-     * Will be assigned userID when SocialServer connection established
+     * TODO: title should be assigned userID when SocialServer connection established
      */
-    private String _title = null;
+    private  String _title = null;
     
     /**
      * Network services to address map.
@@ -417,34 +444,32 @@ public class ClientGUI extends javax.swing.JFrame implements NetworkMessageEvent
     }
     
     private void connectionDialog() {
-        JProgressBar progressBar = new JProgressBar(0,100);
-        progressBar.setValue(0);
-        progressBar.setIndeterminate(true);
-        progressBar.setString("Waiting for Server...");
-        progressBar.setStringPainted(true);
-        System.err.println("Progress Bar created");
-        
-        while (!_serviceToAddressMap.containsService("ServerSocialMC")) { 
-        }
+        /* FIXME: progress monitor
+        ProgressMonitor pm = new ProgressMonitor(this, "Waiting for the Server...", "", 0, 10);
+        pm.setMillisToPopup(100);
+        pm.setProgress(1);
+        */
+        while (!_serviceToAddressMap.containsService("ServerSocialMC"));
+
+        // pm.setProgress(10);
         
         try {
             socialSocket = new Socket(_serviceToAddressMap.getServiceAddress("ServerSocialMC").getAddress(), Network.PORTS_SERVER_SOCIAL);
             NetworkStream newStream = new NetworkStream(socialSocket, _tcpStreamManager);
             _tcpStreamManager.addStream(NetworkStreamManager.SERVERSOCIAL, newStream);
+            newStream.getEventManager().addNetworkMessageEventListener(this);
         } catch (IOException ex) {
             //Logger.getLogger(ClientGUI.class.getName()).log(Level.SEVERE, null, ex);
             System.err.println("IOException in connectionDialog()");
         }
-        //progressBar.setIndeterminate(false);
-        //progressBar.setValue(100);
         loginDialog();
     }
     
     private void loginDialog()
     {
-        //WSYD_Login login = new Login(this, true);
-        login.setLocationRelativeTo(null);
-        login.setVisible(true);
+        //WSYD_Login loginDialog = new Login(this, true);
+        loginDialog.setLocationRelativeTo(null);
+        loginDialog.setVisible(true);
         if (loginSuccessful)
         {
             this.setLocationRelativeTo(null);
@@ -469,40 +494,36 @@ public class ClientGUI extends javax.swing.JFrame implements NetworkMessageEvent
             result = true;
         }
         else {
-            // TODO: wrap a login message with credentials
             NetworkMessage message = new NetworkMessage("Login", null, new MessageLogin(uName, pWord));
-            _tcpStreamManager._tcpStreams.get(NetworkStreamManager.SERVERSOCIAL).write(message);
-            // TODO: send login credentials to server for verification
-            result = true;
+            NetworkStream ns = _tcpStreamManager._tcpStreams.get(NetworkStreamManager.SERVERSOCIAL);
+            if (ns != null) {
+                ns.write(message);                
+                result = true;
+            }
+            else
+                System.err.println(" validateLogin(): do not know where ServerSocial is");
         }
         return result;
     }
     
-    public void regiProfileDialog()
+    public void registrationProfileDialog()
     {
-        EditProfile registration = new EditProfile(this, true);
-        registration.setLocationRelativeTo(null);
-        registration.setVisible(true);
-        if (regiSuccessful)
-        {
-            login.dispose();
-            this.setLocationRelativeTo(null);
-            this.setVisible(true);
-        }
+        registrationDialog.setLocationRelativeTo(null);
+        registrationDialog.setVisible(true);
     }
     
-    public boolean confirmRegistration(String uName, String pWord, String bPlace, String cLocation, TreeSet interests, String bio)
+    public void confirmRegistration(WSYD_Member registrationData)
     {
-        System.out.println(uName);
-        System.out.println(pWord);
-        System.out.println(bPlace);
-        System.out.println(cLocation);
-        
-        System.out.println(bio);
-        //TO DO: If server accepts registration return true
-        regiSuccessful = true;
-        return true;
-        //return false;
+        // TODO: confirmRegistration(): submit registrationDialog data to SocialServer
+        if (registrationData != null) {
+            NetworkMessage message = new NetworkMessage("Register", null, new MessageMember(registrationData));
+            NetworkStream ns = this._tcpStreamManager._tcpStreams.get(NetworkStreamManager.SERVERSOCIAL);
+            if (ns != null) {
+                ns.write(message);
+            }
+            else
+                System.err.println("confirmRegistration(): do not know where SocialServer is");
+        }
     }
     
     
@@ -579,7 +600,37 @@ public class ClientGUI extends javax.swing.JFrame implements NetworkMessageEvent
         NetworkMessage nm = event.getNetworkMessage();
         if (nm == null)
             return;
-        
         System.err.println(MessageFormat.format("Network Message received with intent {0} from sender {1}", nm.getIntent(), nm.getSender()));
+        switch (nm.getIntent()) {
+            case "Login":
+                MessageLogin ml = (MessageLogin) nm.getMessage();
+                if (ml != null) {
+                    this.loginSuccessful = ml._loggedIn;
+                    if (ml._loggedIn)
+                        this.loginDialog.dispose();
+                    else
+                        loginDialog.setUserName("Invalid Login: retry");
+                }
+                break;
+            case "Register":
+                MessageMember mm = (MessageMember) nm.getMessage();
+                if (mm != null) {
+                    if (mm.getRegistered() == MessageMember.STATE.REGISTERED) {
+                        this.myMember = mm.getMember();
+                        this.registrationSuccessful = true;
+                        // dismiss the dialogs and show client's main window
+                        registrationDialog.dispose();
+                        loginDialog.dispose();
+                        this.setTitle("WSYD logged in as " + this.myMember._userName);
+                        this.setLocationRelativeTo(null);
+                        this.setVisible(true);
+                    } else
+                        javax.swing.JOptionPane.showMessageDialog(registrationDialog, mm.getStatus(), "Registration failed", javax.swing.JOptionPane.ERROR_MESSAGE);
+                }
+                break;
+            default:
+                System.err.println(MessageFormat.format("Unhandled NetworkMessage received with intent {0} from sender {1}", nm.getIntent(), nm.getSender()));
+                
+        }
     }
 }