package com.github.noxan.aves.demo;

import java.io.IOException;

import com.github.noxan.aves.auth.AuthException;
import com.github.noxan.aves.auth.accessor.UsernamePassword;
import com.github.noxan.aves.auth.accessor.UsernamePasswordAccessor;
import com.github.noxan.aves.auth.session.SessionManager;
import com.github.noxan.aves.auth.storage.InMemoryUsernamePasswordStorage;
import com.github.noxan.aves.net.Connection;
import com.github.noxan.aves.server.Server;
import com.github.noxan.aves.server.ServerAdapter;
import com.github.noxan.aves.server.SocketServer;

public class AuthServer extends ServerAdapter {
    public static void main(String[] args) {
        Server server = new SocketServer(new AuthServer());
        try {
            server.start();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    private InMemoryUsernamePasswordStorage userStorage;
    private SessionManager manager;

    public AuthServer() {
        userStorage = new InMemoryUsernamePasswordStorage();
        userStorage.addUser("noxan", "123");
        manager = new SessionManager(userStorage);
    }

    @Override
    public void readData(Connection connection, Object data) {
        String parts[] = ((String) data).trim().split(" ");
        String message = parts[0].toUpperCase();
        String[] args = new String[parts.length - 1];
        System.arraycopy(parts, 1, args, 0, args.length);
        try {
            switch (message) {
            case "LOGIN":
                if (args.length > 1) {
                    UsernamePasswordAccessor accessor = new UsernamePassword(args[0], args[1]);
                    try {
                        String user = userStorage.requestUser(accessor);
                        connection.write("WELCOME " + user);
                    } catch (AuthException e) {
                        connection.write("LOGIN ERROR: " + e.getMessage());
                    }
                } else {
                    connection.write("LOGIN ERROR: Invalid parameter(s)");
                }
                break;
            case "LOGOUT":
                connection.write("Not implemented yet!");
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@@ -1682,41 +1682,27 @@
     
-String user = userStor
+if (man
 age
+r
 .request
 User
@@ -1697,20 +1697,23 @@
 .request
-User
+Session
 (accesso
@@ -1713,19 +1713,34 @@
 accessor
-);%0A
+, connection)) %7B%0A 
         
@@ -1747,32 +1747,35 @@
                 
+   
 connection.write
@@ -1781,25 +1781,162 @@
 e(%22W
-ELCOME %22 + user);
+elcome to your session%22);%0A                        %7D else %7B%0A                            connection.write(%22LOGIN ERROR: Session%22);%0A                        %7D
 %0A   

use session manager in auth server