package com.dianping.cat.report.page.app.graph;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.config.app.AppDataService;
import com.dianping.cat.config.app.QueryEntity;
import com.dianping.cat.helper.TimeUtil;
import com.dianping.cat.report.chart.AbstractGraphCreator;
import com.dianping.cat.report.page.LineChart;

public class AppGraphCreator extends AbstractGraphCreator {

	@Inject
	private AppDataService m_appDataService;

	public LineChart buildLineChart(QueryEntity queryEntity1, QueryEntity queryEntity2, String type) {
		LinkedList<double[]> dataList = new LinkedList<double[]>();

		if (queryEntity1 != null) {
			double[] data1 = prepareQueryData(queryEntity1, type);
			dataList.add(data1);
		}

		if (queryEntity2 != null) {
			double[] values2 = prepareQueryData(queryEntity2, type);
			dataList.add(values2);
		}
		return buildChartData(dataList, type);
	}

	private double[] prepareQueryData(QueryEntity queryEntity, String type) {
		double[] value = m_appDataService.queryValue(queryEntity, type);

		return value;
	}

	private String queryType(String type) {
		if (AppDataService.SUCCESS.equals(type)) {
			return "成功率";
		} else if (AppDataService.REQUEST.equals(type)) {
			return "请求数";
		} else if (AppDataService.DELAY.equals(type)) {
			return "成功延时(ms)";
		} else {
			throw new RuntimeException("unexpected query type, type:" + type);
		}
	}

	public LineChart buildChartData(final LinkedList<double[]> dataList, String type) {
		LineChart lineChart = new LineChart();
		lineChart.setId("app");
		lineChart.setHtmlTitle(queryType(type));
		int length = dataList.size();

		for (int i = 0; i < length; i++) {
			double[] data = dataList.get(i);
			lineChart.add("查询" + i++, data);
		}
		return lineChart;
	}

	@Override
	protected Map<Long, Double> convertToMap(double[] data, Date start, int step) {
		Map<Long, Double> map = new LinkedHashMap<Long, Double>();
		int length = data.length;
		long startTime = start.getTime();
		long time = startTime;

		for (int i = 0; i < length; i++) {
			time += step * TimeUtil.ONE_MINUTE;
			map.put(time, data[i]);
		}
		return map;
	}
}

@@ -126,16 +126,39 @@
 edList;%0A
+import java.util.List;%0A
 import j
@@ -679,22 +679,16 @@
 pe) %7B%0A%09%09
-Linked
 List%3Cdou
@@ -698,20 +698,17 @@
 %5B%5D%3E data
-List
+s
  = new L
@@ -822,28 +822,25 @@
 pe);%0A%09%09%09data
-List
+s
 .add(data1);
@@ -942,20 +942,17 @@
 %0A%09%09%09data
-List
+s
 .add(val
@@ -990,20 +990,17 @@
 ata(data
-List
+s
 , type);
@@ -1539,22 +1539,16 @@
 a(final 
-Linked
 List%3Cdou
@@ -1558,20 +1558,17 @@
 %5B%5D%3E data
-List
+s
 , String
@@ -1705,20 +1705,17 @@
 h = data
-List
+s
 .size();
@@ -1776,20 +1776,17 @@
 a = data
-List
+s
 .get(i);
@@ -1786,16 +1786,17 @@
 get(i);%0A
+%0A
 %09%09%09lineC
@@ -1811,19 +1811,23 @@
 (%22%E6%9F%A5%E8%AF%A2%22 + 
-i++
+(i + 1)
 , data);

modify the bug