package org.saiku.service.olap.drillthrough;

import java.util.ArrayList;
import java.util.List;

import org.saiku.olap.dto.SaikuHierarchy;
import org.saiku.olap.dto.SaikuLevel;
import org.saiku.olap.dto.SaikuMember;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;

public class DrillthroughUtils {

	public static SaikuMember findMeasure(List<SaikuMember> measures, final String measureName) {
		return Iterables.find(measures, new Predicate<SaikuMember>() {
			@Override
			public boolean apply(SaikuMember input) {
				return input.getName().equals(measureName);
			}
		});
	}
	
	public static SaikuHierarchy findHierarchy(List<SaikuHierarchy> hierarchies, final String hierarchyName) {
		return Iterables.find(hierarchies, new Predicate<SaikuHierarchy>() {
			@Override
			public boolean apply(SaikuHierarchy input) {
				return input.getName().equals(hierarchyName);
			}
		});
	}

	public static SaikuLevel findLevel(List<SaikuLevel> levels, final String levelName) {
		return Iterables.find(levels, new Predicate<SaikuLevel>() {
			@Override
			public boolean apply(SaikuLevel input) {
				return input.getName().equals(levelName);
			}
		});
	}
	
	public static List<ResultInfo> extractResultInfo(String returns) {
		String[] split = returns.split(",");
		List<ResultInfo> results = new ArrayList<>(); 
		for (String column: split) {
			String[] split2 = column.trim().split("\\.");
			String[] els = new String[split2.length];
			for (int i = 0; i < split2.length; i++) {
				String token = split2[i];
				els[i] = token.trim().replaceAll("[\\[\\]]", "");
			}
			if (els[0].equalsIgnoreCase("Measures")) {
				results.add(new MeasureResultInfo(els[1]));
			} else {
				results.add(new DimensionResultInfo(els[0], els[1], els[2]));
			}
		}
		return results;
	}
	
}

@@ -1425,24 +1425,33 @@
 .%22);%0A%09%09%09
+ArrayList%3C
 String
-%5B%5D
+%3E
  els = n
@@ -1457,29 +1457,21 @@
 new 
-String%5Bsplit2.length%5D
+ArrayList%3C%3E()
 ;%0A%09%09
@@ -1554,14 +1554,13 @@
 %09els
-%5Bi%5D = 
+.add(
 toke
@@ -1594,16 +1594,17 @@
 %5D%5D%22, %22%22)
+)
 ;%0A%09%09%09%7D%0A%09
@@ -1612,19 +1612,23 @@
 %09if (els
-%5B0%5D
+.get(0)
 .equalsI
@@ -1693,19 +1693,23 @@
 Info(els
-%5B1%5D
+.get(1)
 ));%0A%09%09%09%7D
@@ -1716,16 +1716,41 @@
  else %7B%0A
+%09%09%09%09if(els.size()%3E=3) %7B%0A%09
 %09%09%09%09resu
@@ -1788,30 +1788,143 @@
 (els
-%5B0%5D, els%5B1%5D, els%5B2%5D));
+.get(0), els.get(1), els.get(2)));%0A%09%09%09%09%7D%0A%09%09%09%09else%7B%0A%09%09%09%09%09results.add(new DimensionResultInfo(els.get(0), els.get(0), els.get(1)));%0A%09%09%09%09%7D
 %0A%09%09%09

update drillthrough utils to not die