package de.tu_darmstadt.tk.SmartHomeNetworkSim.core.anomalydetectors;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map.Entry;

import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Packet;
import weka.classifiers.AbstractClassifier;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.classifiers.trees.J48;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffSaver;

public class NNAnomalyDetector extends BaseAnomalyDetector {
	/**
	 * Classifier
	 */
	private MultilayerPerceptron mlp;
	
	public NNAnomalyDetector() {
		super();
		// Initialize Classifier
		mlp = new MultilayerPerceptron();
		//mlp.setSeed(42);
		
	}
	/**
	 * Try to classify the given packets and detect anomalies
	 * @param packets packets to be classified
	 * @throws Exception 
	 */
	@Override
	public boolean classifyInstance(Instance instance) throws Exception {
		
		mlp.classifyInstance(instance);
		return true;
	}	
	
	/**
	 * Train the model using the given instances
	 * @param instances training set, which should be learned
	 */
	@Override
	public void trainModel(Instances instances) {
		try {
			
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			String filepath = "./data/NNTrainingSet_Directions_" + timestamp.getNanos() + ".arff";
			ArffSaver saver = new ArffSaver();
			saver.setInstances(dataset);
			saver.setFile(new File(filepath));
			saver.writeBatch();
			
			instances.setClassIndex(instances.numAttributes() - 1);
			
			mlp.buildClassifier(instances);
		} catch (Exception e) {
			System.out.println("NN classifing failed");
			e.printStackTrace();
		}
	}
	
	@Override
	public void saveModel() throws Exception {
		weka.core.SerializationHelper.write("./data/models/mlp", mlp);
	}
}
