package innovimax.mixthem.operation;

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

import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;

/**
* <p>Zips two lines on a common field.</p>
* @see ILineOperation
* @author Innovimax
* @version 1.0
*/
public class DefaultLineZipping extends AbstractLineOperation {
	
	private final ZipType type;
	
	/**
	* Constructor
	* @param type The type of zip to process
 	* @param params The list of parameters (maybe empty)
	* @see innovimax.mixthem.operation.ZipType
	* @see innovimax.mixthem.arguments.RuleParam
	* @see innovimax.mixthem.arguments.ParamValue
	*/
	public DefaultLineZipping(ZipType type, Map<RuleParam, ParamValue> params) {
		super(params);
		this.type = type;		
	}
	
	@Override
	public String process(String line1, String line2) throws MixException {
		String zip = null;
		String sep = DEFAULT_ZIP_SEPARATOR;
		if (this.params.containsKey(RuleParam._ZIP_SEP)) {
			sep = this.params.get(RuleParam._ZIP_SEP).asString();
		}		
		switch (this.type) {
			case _LINE:
				zip = (line1 != null ? line1 : "") + sep + (line2 != null ? line2 : "");
				break;
			case _CELL:					
				Iterator<String> iterator1 = line1 != null ? Arrays.asList(line1.split(DEFAULT_SPLIT_CELL_REGEX )).iterator() : Collections.emptyIterator();
				Iterator<String> iterator2 = line2 != null ? Arrays.asList(line2.split(DEFAULT_SPLIT_CELL_REGEX )).iterator() : Collections.emptyIterator();				
				StringBuffer buf = new StringBuffer();
				while (iterator1.hasNext() || iterator2.hasNext()) {						
					String cell1 = iterator1.hasNext() ? iterator1.next() : "";
					String cell2 = iterator2.hasNext() ? iterator2.next() : "";					
					if (buf.length() > 0) {						
						buf.append(DEFAULT_CELL_SEPARATOR);
					}					
					buf.append(cell1 + sep + cell2);					
				}
				zip = buf.toString();
		}
		return zip;
	}

}

@@ -519,16 +519,43 @@
 e type;%0A
+%09private final String sep;%0A
 %09%0A%09/**%0A%09
@@ -924,274 +924,240 @@
 ype;
+%0A
 %09%09
-%0A%09%7D%0A%09%0A%09@Override%0A%09public String process(String line1, String line2) throws MixException %7B%0A%09%09String zip = null;%0A%09%09String sep = DEFAULT_ZIP_SEPARATOR;%0A%09%09if (this.params.containsKey(RuleParam._ZIP_SEP)) %7B%0A%09%09%09sep = this.params.get(RuleParam._ZIP_SEP).asString();%0A%09%09%7D%09%09
+this.sep = params.containsKey(RuleParam._ZIP_SEP) ? params.get(RuleParam._ZIP_SEP).asString() : DEFAULT_ZIP_SEPARATOR;%09%0A%09%7D%0A%09%0A%09@Override%0A%09public String process(String line1, String line2) throws MixException %7B%0A%09%09String zip = null;
 %0A%09%09s
@@ -1232,16 +1232,21 @@
 : %22%22) + 
+this.
 sep + (l
@@ -1952,16 +1952,21 @@
 cell1 + 
+this.
 sep + ce

move params setting to constructor