package innovimax.mixthem.operation;

import static innovimax.mixthem.MixConstants.*;
import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.ParamValue;
import innovimax.mixthem.arguments.RuleParam;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* <p>Joins two lines on a common field.</p>
* @see ILineOperation
* @author Innovimax
* @version 1.0
*/
public class DefaultLineJoining extends AbstractLineOperation {
	
	/**
 	* @param params The list of parameters (maybe empty)
	* @see innovimax.mixthem.operation.RuleParam
	* @see innovimax.mixthem.operation.ParamValue
	*/
	public DefaultLineJoining(Map<RuleParam, ParamValue> params) {
		super(params);
	}	

	@Override
	public String process(String line1, String line2) throws MixException {
		String join = null;
		int col1 = 1;
		int col2 = 1;
		if (this.params.containsKey(RuleParam._JOIN_COL1)) {
			col1 = this.params.get(RuleParam._JOIN_COL1).asInt();
			col2 = col1;
		}
		if (this.params.containsKey(RuleParam._JOIN_COL2)) {
			col2 = this.params.get(RuleParam._JOIN_COL2).asInt();			
		}
		List<String> list1 = Arrays.asList(line1.split(DEFAULT_SPLIT_CELL_REGEX));
		List<String> list2 = Arrays.asList(line2.split(DEFAULT_SPLIT_CELL_REGEX));		
		if (list1.size() >= col1 && list2.size() >= col2 && list1.get(col1 - 1).equals(list2.get(col2 - 1))) {
			String part1 = list1.get(col1 - 1);
			String part2 = list1.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(DEFAULT_CELL_SEPARATOR));
			String part3 = list2.stream().filter(s -> !s.equals(part1)).collect(Collectors.joining(DEFAULT_CELL_SEPARATOR));
			join = part1 + DEFAULT_CELL_SEPARATOR  + part2 + DEFAULT_CELL_SEPARATOR + part3;				
		}		
		return join;
	}

}

@@ -842,16 +842,56 @@
 = null;%0A
+%09%09if (line1 !=null && line2 != null) %7B%0A%09
 %09%09int co
@@ -898,16 +898,17 @@
 l1 = 1;%0A
+%09
 %09%09int co
@@ -913,24 +913,25 @@
 col2 = 1;%0A%09%09
+%09
 if (this.par
@@ -967,24 +967,25 @@
 IN_COL1)) %7B%0A
+%09
 %09%09%09col1 = th
@@ -1029,16 +1029,17 @@
 sInt();%0A
+%09
 %09%09%09col2 
@@ -1048,18 +1048,20 @@
 col1;%0A%09%09
+%09
 %7D%0A
+%09
 %09%09if (th
@@ -1110,16 +1110,17 @@
 )) %7B%0A%09%09%09
+%09
 col2 = t
@@ -1168,22 +1168,24 @@
 t();%09%09%09%0A
+%09
 %09%09%7D%0A%09%09
+%09
 List%3CStr
@@ -1251,16 +1251,17 @@
 EGEX));%0A
+%09
 %09%09List%3CS
@@ -1331,16 +1331,17 @@
 EX));%09%09%0A
+%09
 %09%09if (li
@@ -1436,24 +1436,25 @@
 - 1))) %7B%0A%09%09%09
+%09
 String part1
@@ -1477,16 +1477,17 @@
 1 - 1);%0A
+%09
 %09%09%09Strin
@@ -1597,16 +1597,17 @@
 R));%0A%09%09%09
+%09
 String p
@@ -1711,16 +1711,17 @@
 ATOR));%0A
+%09
 %09%09%09join 
@@ -1806,11 +1806,14 @@
 %09%0A%09%09
-%7D
+%09%7D%0A
 %09%09
+%7D
 %0A%09%09r

update join operation