package org.mokey.mapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.mokey.mapping.configurations.Configuration;
import org.mokey.mapping.dal.DataAccessor;
import org.mokey.mapping.tuples.Tuple;

public class Mapper{
	private static Logger log = Logger.getLogger("Mapper");
	
	private Configuration config = null;
	private DataAccessor dao = null;
	
	public Mapper(Configuration config, DataAccessor dao){
		this.config = config;
		this.dao = dao;
	}
	
	public Tuple<?>[] map(Tuple<?>[] tuples) {
		if(tuples.length != this.config.tupleCount()){
			log.error(String.format("Count[%s, %s] of input tuples is not correct", 
					tuples.length, this.config.tupleCount()));
			return null;
		}
		log.debug("Input tuples is :" + StringUtils.join(tuples, ","));
		
		Tuple<?>[] result = null;
		double minValue = Double.MAX_VALUE;
		List<Tuple<?>[]> lines = this.dao.getTargetCollection(tuples);
		
		log.debug("Target collectiion size is: " + lines.size());
		
		Map<Tuple<?>[], Double> candiate = new HashMap<Tuple<?>[], Double>();
		for (Tuple<?>[] line : lines) {
			if(line.length != this.config.tupleCount()){
				log.error(String.format("Invalid target truples, cause: tuples count[%s, %s] not matched to the config",
						line.length, this.config.tupleCount()));
				continue;
			}
			double value = 0.0;
			for (int i = 0; i < line.length; i++) {
				value += line[i].diff(tuples[i]) * this.config.getWeight(i).getWeight();
			}
			if(value < minValue)
			{
				minValue = value;
				result = line;
			}
			if(value <= this.config.getMaxValue() && !candiate.containsKey(line))
				candiate.put(line, value);
			log.debug(String.format("Caculate the value of tuple[%s] is : %s", StringUtils.join(line, ","), value));
		}
		
		log.debug(String.format("Final value of mapped tuple[%s] is : %s", StringUtils.join(result, ","), minValue));
		return result;
	}
}

@@ -1600,32 +1600,13 @@
 ue;%0A
-%09%09%09%09result = line;%0A
 %09%09%09%7D%0A
+
 %09%09%09i
@@ -1819,17 +1819,206 @@
 ;%0A%09%09%7D%0A%09%09
-%0A
+minValue = Double.MAX_VALUE;%0A%09%09for (Tuple%3C?%3E%5B%5D tp : candiate.keySet()) %7B%0A%09%09%09if(candiate.get(tp) %3C minValue)%7B%0A%09%09%09%09result = tp;%0A%09%09%09%09minValue = candiate.get(tp);%0A%09%09%09%7D%0A%09%09%7D%0A%09%09if(null != result)%0A%09
 %09%09log.de
@@ -2121,16 +2121,82 @@
 alue));%0A
+%09%09else%0A%09%09%09log.debug(%22Final value of mapped tuple%5B%25s%5D is : null%22);%0A
 %09%09return

FIX ISSUE