package com.electrotank.electroserver.plugins;

import com.electrotank.electroserver.plugins.AbstractPlugin;
import com.electrotank.electroserver.plugins.PluginException;
import com.electrotank.electroserver.plugins.utilities.PluginHelper;

import java.util.HashMap;
import java.util.Map;

/*
 * This is an example java plugin for ElectroServer. You can tell the server to use it by 
   including this section in your configuration.xml file (inside the <Plugins> node).
 
	<Plugin>
		<Name>SimpleJavaPlugin</Name>
		<Type>Java</Type>
		<Scope>Room</Scope>
		<File>com.electrotank.electroserver.plugins.SimpleJavaPlugin</File>
		<Variables/>
	</Plugin>
 
 */

public class SimpleJavaPlugin extends AbstractPlugin {
    
    public String timeFormat;
    
    public void pluginInit(Map parameters) throws PluginException {
        timeFormat = (String) parameters.get("timeFormat");
    }
    
    public void pluginRequest(Map parameters) throws PluginException {
        
        String caller = (String)parameters.get(EXECUTING_USER_NAME);
        String method = (String)parameters.get(METHOD);
        
        if(method.equals("Calculate")) {
            int iterations = Integer.parseInt( (String)parameters.get("iterations"));
            long result = calculate(iterations);
            returnToUser(caller, Long.toString(result));
        }
        
    }
    
    public void pluginDestroy() throws PluginException {
    }
    
    public void returnToUser(String caller, String value) {
        
        Map variables = new HashMap();
        variables.put("CalculationResult", value);
        
        PluginHelper helper = getPluginHelper();
        helper.sendPrivateMessage(caller, "Results", variables);
    }
    
    public long calculate(int num) {
        long start = System.currentTimeMillis();
        double result;
        for (int i = 0; i < num; i++) {
            result = Math.sin(num);
        }
        long end = System.currentTimeMillis();
        long totalTime = end - start;
        
        if(timeFormat.equals("miliseconds")) {
            //do nothing, it is already miliseconds
        } else if (timeFormat == "seconds") {
            totalTime /= 1000;
        }
        return totalTime;
    }
}
