package com.electrotank.electroserver.plugins;

import com.electrotank.electroserver.plugins.AbstractEventHandler;
import com.electrotank.electroserver.plugins.EventException;
import com.electrotank.electroserver.plugins.LoginEventInterface;
import com.electrotank.electroserver.plugins.utilities.EventHelper;
import com.electrotank.electroserver.plugins.utilities.LoginResponse;

import java.util.HashMap;
import java.util.Map;


/*
 * This example event handler dynamically assigns a name for a user if the connect to the server and fail to pass one. 
 * This is the illustrate how you can set your own if needed.
  You can tell the server to use this handler by including this section in your configuration.xml file.
 
 	<EventHandlers>
	    <EventHandler>
                <Name>Dynamic Name Login Handler</Name>
                <Type>Java</Type>
                <Event>Login</Event>
                <File>com.electrotank.electroserver.plugins.DynamicNameLoginEventHandlerExample</File>
                <Variables />
            </EventHandler>
	</EventHandlers>
 
 */
public class DynamicNameLoginEventHandlerExample extends AbstractEventHandler implements LoginEventInterface {

    // This behaves the same as the pluginInit method, the parameters from the configuration file
    // are passed in directly to this Map
    public void eventInit(Map parameters) throws EventException {
        // Do nothing in this example
    }
        
    // This method is invoked when a user attempts to log into the server. They are sucessful or not depending
    // on the contents of the LoginResponse object.
    public LoginResponse login(String userName, String password, Map eventVariables) throws EventException {
        
        boolean status = true;
        String message = null;
        
        // Get access to the event helper (just like plugin helper, but for event handlers)
        EventHelper helper = getEventHelper();
        
        // Create the login response for the user
        LoginResponse response = new LoginResponse(status, message);
        
        // If the username is null of if its "testName", then assign then a new name
        if(userName == null || userName.length() == 0 || userName.equals("testName")) {
            userName = "user_" + System.currentTimeMillis();
            response.setUsername(userName);
        }
        
        // Return the response
        return response;
        
    } // end login method
    
}
